-
Notifications
You must be signed in to change notification settings - Fork 1
/
symbol.go
130 lines (112 loc) · 2.09 KB
/
symbol.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package lang
import (
"strings"
)
type Symbol struct {
meta IPersistentMap
ns string
name string
}
// NewSymbol creates a new symbol.
func NewSymbol(s string) *Symbol {
ns, name := "", s
idx := strings.Index(s, "/")
if idx != -1 && s != "/" && s[0] != '/' {
ns = s[:idx]
name = s[idx+1:]
}
if !isValidSymbol(ns, name) {
panic(NewIllegalArgumentError("invalid symbol: " + s))
}
return &Symbol{
ns: ns,
name: name,
}
}
func InternSymbol(ns, name interface{}) *Symbol {
if ns == nil {
return NewSymbol(name.(string))
}
if ns, ok := ns.(string); ok {
if ns == "" {
return NewSymbol(name.(string))
}
}
return NewSymbol(ns.(string) + "/" + name.(string))
}
func (s *Symbol) Namespace() string {
return s.ns
}
func (s *Symbol) Name() string {
return s.name
}
func (s *Symbol) FullName() string {
return s.String()
}
func isValidSymbol(ns, name string) bool {
var full string
if ns == "" {
full = name
} else {
full = ns + "/" + name
}
// early special case for the division operator /
if full == "/" {
return true
}
if name == "" {
// empty name
return false
}
if ns == "" && full[0] == '/' {
// empty namespace
return false
}
if strings.HasSuffix(name, ":") {
// name ends with a colon (match clojure)
return false
}
if strings.Contains(name, "::") {
// name contains double colon
//
// NB: clojure reader rejects this, but clojure.core/symbol
// accepts it
return false
}
return true
}
func (s *Symbol) String() string {
if s.ns == "" {
return s.name
}
return s.ns + "/" + s.name
}
func (s *Symbol) Equals(v interface{}) bool {
if s == v {
return true
}
other, ok := v.(*Symbol)
if !ok {
return false
}
if other == nil {
return false
}
return s.ns == other.ns && s.name == other.name
}
func (s *Symbol) Meta() IPersistentMap {
return s.meta
}
func (s *Symbol) WithMeta(meta IPersistentMap) interface{} {
if s.meta == meta {
return s
}
symCopy := *s
symCopy.meta = meta
return &symCopy
}
func (s *Symbol) Hash() uint32 {
h := getHash()
h.Write([]byte(s.ns + "/" + s.name))
return h.Sum32() ^ symbolHashMask
}