-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpairs.go
More file actions
94 lines (80 loc) · 2.02 KB
/
Copy pathpairs.go
File metadata and controls
94 lines (80 loc) · 2.02 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
package enc
import (
"bytes"
"fmt"
"reflect"
"strings"
"github.com/Aize-Public/forego/ctx"
)
// ordered pairs, used mostly internally when Marshalling structs, to preserve the order of the fields
// can be used anywhere else where the order matters
type Pairs []Pair
var _ Node = Pairs{}
func (this Pairs) AsMap() Map {
out := Map{}
for _, p := range this {
out[p.JSON] = p.Value
}
return out
}
func (this Pairs) native() any {
out := map[string]any{}
for _, p := range this {
out[p.Name] = p.Value.native()
}
return out
}
func (this Pairs) String() string {
list := []string{}
for _, p := range this {
list = append(list, fmt.Sprintf("%q:%#s", p.JSON, p.Value))
}
return "enc.Pairs{" + strings.Join(list, ", ") + "}"
}
func (this Pairs) GoString() string {
list := []string{}
for _, p := range this {
list = append(list, fmt.Sprintf("%q:%#s", p.Name, p.Value))
}
return "enc.Pairs{" + strings.Join(list, ", ") + "}"
}
func (this Pairs) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
buf.WriteString("{")
for i, p := range this {
if i > 0 {
buf.WriteString(", ")
}
buf.Write(mustJSON(p.JSON))
buf.WriteString(": ")
buf.Write(mustJSON(p.Value))
}
buf.WriteString("}")
return buf.Bytes(), nil
}
func (this Pairs) Find(name string) Node {
for _, p := range this {
if p.JSON == name {
return p.Value
}
}
return nil
}
func (this Pairs) unmarshalInto(c ctx.C, handler Handler, into reflect.Value) error {
// to make it easier to maintain, we convert to a map and reuse that code
m := Map{}
for _, p := range this {
m[p.JSON] = p.Value
// using the p.JSON is the only option, even tho it looks wrong
// the reason for this is that enc.Map{} does not know fields and maps to objects directly
}
return m.unmarshalInto(c, handler, into)
}
type Pair struct {
Name string
JSON string // FIXME(oha): we can't really support Name and JSON, we must collapse to name and have all the tags agree
Value Node
}
func (this Pair) String() string {
return fmt.Sprintf("%q:%s", this.JSON, this.Value)
}