-
Notifications
You must be signed in to change notification settings - Fork 0
/
orderedmap.go
91 lines (71 loc) · 1.7 KB
/
orderedmap.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
package orderedmapjson
import (
"bytes"
"encoding/json"
"fmt"
"github.com/elliotchance/orderedmap/v3"
"strings"
)
type orderedMap[V any] struct {
*orderedmap.OrderedMap[string, V]
escapeHTML bool
}
func newOrderedMap[V any]() *orderedMap[V] {
return &orderedMap[V]{
OrderedMap: orderedmap.NewOrderedMap[string, V](),
escapeHTML: true, // Default to true for consistency with encoding/json
}
}
func newOrderedMapWithCapacity[V any](capacity int) *orderedMap[V] {
return &orderedMap[V]{
OrderedMap: orderedmap.NewOrderedMapWithCapacity[string, V](capacity),
escapeHTML: true, // Default to true for consistency with encoding/json
}
}
func (m *orderedMap[V]) SetEscapeHTML(on bool) {
m.escapeHTML = on
}
func (m *orderedMap[V]) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
buf.WriteByte('{')
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(m.escapeHTML)
index := 0
for k, v := range m.AllFromFront() {
if index > 0 {
buf.WriteByte(',')
}
if err := encoder.Encode(k); err != nil {
return nil, err
}
buf.WriteByte(':')
if err := encoder.Encode(v); err != nil {
return nil, err
}
index++
}
buf.WriteByte('}')
return buf.Bytes(), nil
}
func (m *orderedMap[V]) String() string {
builder := strings.Builder{}
builder.WriteString("{")
index := 0
for k, v := range m.AllFromFront() {
if index > 0 {
builder.WriteString(",")
}
builder.WriteString(fmt.Sprintf("%v:%v", k, v))
index++
}
builder.WriteString("}")
return builder.String()
}
func (m *orderedMap[V]) Copy() *orderedMap[V] {
mm := newOrderedMapWithCapacity[V](m.Len())
mm.SetEscapeHTML(m.escapeHTML)
for key, value := range m.AllFromFront() {
mm.Set(key, value)
}
return mm
}