-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
113 lines (100 loc) · 2.11 KB
/
hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package gmnlisp
import (
"context"
"errors"
"fmt"
"io"
)
type _Hash map[Node]Node
func (h _Hash) Equals(other Node, mode EqlMode) bool {
return false
}
func (h _Hash) PrintTo(w io.Writer, mode PrintMode) (int, error) {
var wc writeCounter
dem := '{'
for key, val := range h {
if wc.Try(fmt.Fprintf(w, "%c%#v:%#v", dem, key, val)) {
return wc.Result()
}
dem = ','
}
wc.Try(w.Write([]byte{'}'}))
return wc.Result()
}
func (h _Hash) Eval(ctx context.Context, w *World) (Node, error) {
return h, nil
}
func cmdMakeHashTable(ctx context.Context, w *World, _ Node) (Node, error) {
return make(_Hash), nil
}
var ErrExpectedHash = errors.New("expected Hash-table")
func canUseHashKey(value Node) bool {
switch value.(type) {
case String:
return true
case Symbol:
return true
case Integer:
return true
case Float:
return true
case Rune:
return true
case Keyword:
return true
}
return false
}
func funGetHash(ctx context.Context, w *World, args []Node) (Node, error) {
hash, ok := args[1].(_Hash)
if !ok {
return nil, ErrExpectedHash
}
if !canUseHashKey(args[0]) {
return nil, ErrNotSupportType
}
value, ok := hash[args[0]]
if !ok {
return Null, nil
}
return value, nil
}
func funSetHash(ctx context.Context, w *World, args []Node) (Node, error) {
hash, ok := args[2].(_Hash)
if !ok {
return nil, ErrExpectedHash
}
if !canUseHashKey(args[1]) {
return nil, ErrNotSupportType
}
hash[args[1]] = args[0]
return args[0], nil
}
func funHashTableCount(ctx context.Context, w *World, args []Node) (Node, error) {
hash, ok := args[0].(_Hash)
if !ok {
return nil, ErrExpectedHash
}
return Integer(len(hash)), nil
}
func funRemoveHash(ctx context.Context, w *World, args []Node) (Node, error) {
hash, ok := args[1].(_Hash)
if !ok {
return nil, ErrExpectedHash
}
if !canUseHashKey(args[0]) {
return nil, ErrNotSupportType
}
delete(hash, args[0])
return Null, nil
}
func funClearHash(ctx context.Context, w *World, args []Node) (Node, error) {
hash, ok := args[0].(_Hash)
if !ok {
return nil, ErrExpectedHash
}
for key := range hash {
delete(hash, key)
}
return Null, nil
}