Debian Codegraph @

model/orderedmap/map.go

raw symbols SCIP
1 package orderedmap
2
3 import (
4 "reflect"
5 )
6
7 // KeyValue is a single key value pair from a *Map.
8 type KeyValue struct {
9 Key string
10 Value any
11 }
12
13 // NewMap returns a new *Map that has its values initialised.
14 func NewMap() *Map {
15 keys := make([]string, 0)
16 data := make(map[string]any)
17 return &Map{
18 keys: keys,
19 data: data,
20 }
21 }
22
23 // FromMap creates a *Map from the input map.
24 // Note that while the contents will be ordered, the ordering is not
25 // guaranteed since the input map is unordered.
26 func FromMap(source map[string]any) *Map {
27 m := NewMap()
28 for k, v := range source {
29 m.Set(k, v)
30 }
31 return m
32 }
33
34 // Map is a map implementation that maintains ordering of keys.
35 type Map struct {
36 // keys contains the keys within the map in the order they were added.
37 keys []string
38 // data contains the actual map data.
39 data map[string]any
40 }
41
42 func (m *Map) Len() int {
43 return len(m.keys)
44 }
45
46 func (m *Map) Equal(other *Map) bool {
47 if m.Len() != other.Len() {
48 return false
49 }
50
51 for i, k := range m.keys {
52 if k != other.keys[i] {
53 return false
54 }
55
56 if !reflect.DeepEqual(m.data[k], other.data[k]) {
57 return false
58 }
59 }
60
61 return true
62 }
63
64 // Get returns the value found under the given key.
65 func (m *Map) Get(key string) (any, bool) {
66 v, ok := m.data[key]
67 return v, ok
68 }
69
70 // Set sets a value under the given key.
71 func (m *Map) Set(key string, value any) *Map {
72 if _, ok := m.data[key]; ok {
73 m.data[key] = value
74 } else {
75 m.keys = append(m.keys, key)
76 m.data[key] = value
77 }
78 return m
79 }
80
81 // Delete deletes the value found under the given key.
82 func (m *Map) Delete(key string) *Map {
83 // Delete the data entry.
84 delete(m.data, key)
85
86 // Remove the item from the keys.
87 foundIndex := -1
88 for i, k := range m.keys {
89 if k == key {
90 foundIndex = i
91 break
92 }
93 }
94
95 if foundIndex >= 0 {
96 m.keys = append((m.keys)[:foundIndex], (m.keys)[foundIndex+1:]...)
97 }
98
99 return m
100 }
101
102 // KeyValues returns the KeyValue pairs within the map, in the order that they were added.
103 func (m *Map) KeyValues() []KeyValue {
104 res := make([]KeyValue, 0)
105 for _, key := range m.keys {
106 res = append(res, KeyValue{
107 Key: key,
108 Value: m.data[key],
109 })
110 }
111 return res
112 }
113
114 // Keys returns all the keys from the map.
115 func (m *Map) Keys() []string {
116 return m.keys
117 }
118
119 // UnorderedData returns all the data from the map.
120 func (m *Map) UnorderedData() map[string]any {
121 return m.data
122 }