File tree Expand file tree Collapse file tree 2 files changed +82
-0
lines changed Expand file tree Collapse file tree 2 files changed +82
-0
lines changed Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ package object
33import (
44 "bytes"
55 "fmt"
6+ "hash/fnv"
67 "strings"
78
89 "github.com/AvicennaJr/Nuru/ast"
@@ -20,6 +21,7 @@ const (
2021 STRING_OBJ = "NENO"
2122 BUILTIN_OBJ = "BUILTIN"
2223 ARRAY_OBJ = "ARRAY"
24+ DICT_OBJ = "DICT"
2325)
2426
2527type Object interface {
@@ -129,3 +131,61 @@ func (ao *Array) Inspect() string {
129131
130132 return out .String ()
131133}
134+
135+ type HashKey struct {
136+ Type ObjectType
137+ Value uint64
138+ }
139+
140+ func (b * Boolean ) HashKey () HashKey {
141+ var value uint64
142+
143+ if b .Value {
144+ value = 1
145+ } else {
146+ value = 0
147+ }
148+
149+ return HashKey {Type : b .Type (), Value : value }
150+ }
151+
152+ func (i * Integer ) HashKey () HashKey {
153+ return HashKey {Type : i .Type (), Value : uint64 (i .Value )}
154+ }
155+
156+ func (s * String ) HashKey () HashKey {
157+ h := fnv .New64a ()
158+ h .Write ([]byte (s .Value ))
159+
160+ return HashKey {Type : s .Type (), Value : h .Sum64 ()}
161+ }
162+
163+ type DictPair struct {
164+ Key Object
165+ Value Object
166+ }
167+
168+ type Dict struct {
169+ Pairs map [HashKey ]DictPair
170+ }
171+
172+ func (d * Dict ) Type () ObjectType { return DICT_OBJ }
173+ func (d * Dict ) Inspect () string {
174+ var out bytes.Buffer
175+
176+ pairs := []string {}
177+
178+ for _ , pair := range d .Pairs {
179+ pairs = append (pairs , fmt .Sprintf ("%s: %s" , pair .Key .Inspect (), pair .Value .Inspect ()))
180+ }
181+
182+ out .WriteString ("{" )
183+ out .WriteString (strings .Join (pairs , ", " ))
184+ out .WriteString ("}" )
185+
186+ return out .String ()
187+ }
188+
189+ type Hashable interface {
190+ HashKey () HashKey
191+ }
Original file line number Diff line number Diff line change 1+ package object
2+
3+ import "testing"
4+
5+ func TestStringHashKey (t * testing.T ) {
6+ hello1 := & String {Value : "Hello World" }
7+ hello2 := & String {Value : "Hello World" }
8+ diff1 := & String {Value : "My name is Avi" }
9+ diff2 := & String {Value : "My name is Avi" }
10+
11+ if hello1 .HashKey () != hello2 .HashKey () {
12+ t .Errorf ("string with the same content have different dict keys" )
13+ }
14+
15+ if diff1 .HashKey () != diff2 .HashKey () {
16+ t .Errorf ("String with the same content have different dict keys" )
17+ }
18+
19+ if hello1 .HashKey () == diff1 .HashKey () {
20+ t .Errorf ("Strings with different content have the same dict keys" )
21+ }
22+ }
You can’t perform that action at this time.
0 commit comments