-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathobject_string.go
83 lines (66 loc) · 1.94 KB
/
object_string.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
package object
import (
"hash/fnv"
"strconv"
"unicode/utf8"
)
// String wraps string and implements the Object interface.
type String struct {
// Value holds the string value this object wraps.
Value string
// Offset holds our iteration-offset
offset int
}
// Type returns the type of this object.
func (s *String) Type() Type {
return STRING
}
// Inspect returns a string-representation of the given object.
func (s *String) Inspect() string {
return s.Value
}
// True returns whether this object wraps a true-like value.
//
// Used when this object is the conditional in a comparison, etc.
func (s *String) True() bool {
return (s.Value != "")
}
// ToInterface converts this object to a go-interface, which will allow
// it to be used naturally in our sprintf/printf primitives.
//
// It might also be helpful for embedded users.
func (s *String) ToInterface() interface{} {
return s.Value
}
// Reset implements the Iterable interface, and allows the contents
// of the string to be reset to allow re-iteration.
func (s *String) Reset() {
s.offset = 0
}
// Next implements the Iterable interface, and allows the contents
// of our string to be iterated over.
func (s *String) Next() (Object, Object, bool) {
if s.offset < utf8.RuneCountInString(s.Value) {
s.offset++
// Get the characters as an array of runes
chars := []rune(s.Value)
// Now index
val := String{Value: string(chars[s.offset-1])}
return &val, &Integer{Value: int64(s.offset - 1)}, true
}
return nil, &Integer{Value: 0}, false
}
// HashKey returns a hash key for the given object.
func (s *String) HashKey() HashKey {
h := fnv.New64a()
h.Write([]byte(s.Value))
return HashKey{Type: s.Type(), Value: h.Sum64()}
}
// JSON converts this object to a JSON string.
func (s *String) JSON() (string, error) {
return strconv.Quote(s.Value), nil
}
// Ensure this object implements the expected interfaces
var _ Hashable = &String{}
var _ Iterable = &String{}
var _ JSONAble = &String{}