Repository navigation
Expand file tree
/
Copy pathRef.go
More file actions
103 lines (89 loc) · 2.21 KB
/
Copy pathRef.go
File metadata and controls
103 lines (89 loc) · 2.21 KB
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
package haystack
import (
"encoding/json"
"errors"
"strings"
)
// Ref wraps a string reference identifier and display name.
type Ref struct {
id string
dis string // Optional
}
// NewRef creates a new Ref. For display-less refs, use an empty string dis: ""
func NewRef(id string, dis string) Ref {
return Ref{id: id, dis: dis}
}
// Id returns the ref identifier
func (ref Ref) Id() string {
return ref.id
}
// Dis returns the ref display string
func (ref Ref) Dis() string {
return ref.dis
}
// ToZinc representes the object as: "@<id> \"[dis]\""
func (ref Ref) ToZinc() string {
result := "@" + ref.id
if ref.dis != "" {
dis := Str{val: ref.dis}
result = result + " " + dis.ToZinc()
}
return result
}
// MarshalJSON representes the object as: "r:<id> [dis]"
func (ref Ref) MarshalJSON() ([]byte, error) {
result := "r:" + ref.id
if ref.dis != "" {
result = result + " " + ref.dis
}
return json.Marshal(result)
}
// UnmarshalJSON interprets the json value: "r:<id> [dis]"
func (ref *Ref) UnmarshalJSON(buf []byte) error {
var jsonStr string
err := json.Unmarshal(buf, &jsonStr)
if err != nil {
return err
}
newRef, newErr := refFromJSON(jsonStr)
*ref = newRef
return newErr
}
func refFromJSON(jsonStr string) (Ref, error) {
if !strings.HasPrefix(jsonStr, "r:") {
return Ref{}, errors.New("value does not begin with 'r:'")
}
refStr := jsonStr[2:]
firstSpaceIndex := strings.Index(refStr, " ")
if firstSpaceIndex == -1 {
return NewRef(refStr, ""), nil
} else {
id := refStr[:firstSpaceIndex]
dis := refStr[firstSpaceIndex+1:]
return NewRef(id, dis), nil
}
}
// MarshalHayson representes the object as: "{"_kind":"ref","val":<id>,["dis":<dis>]}"
func (ref Ref) MarshalHayson() ([]byte, error) {
buf := strings.Builder{}
buf.WriteString("{\"_kind\":\"ref\",\"val\":\"")
buf.WriteString(ref.id)
buf.WriteString("\"")
if ref.dis != "" {
buf.WriteString(",\"dis\":\"")
buf.WriteString(ref.dis)
buf.WriteString("\"")
}
buf.WriteString("}")
return []byte(buf.String()), nil
}
func IsIdChar(char rune) bool {
return ('a' <= char && char <= 'z') ||
('A' <= char && char <= 'Z') ||
('0' <= char && char <= '9') ||
char == '_' ||
char == ':' ||
char == '-' ||
char == '.' ||
char == '~'
}