-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
204 lines (176 loc) · 4.73 KB
/
event.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package event
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
var (
ErrKeyExists = errors.New("key already exists")
ErrTargetKeyNotObject = errors.New("target key is not an object")
ErrEmptyKey = errors.New("key name is empty")
)
type Event struct {
fields map[string]*Value
}
// New returns a new Event.
func New() *Event {
return &Event{}
}
func (e *Event) init() {
e.fields = map[string]*Value{}
}
// Put puts a value into the map. If the key already exists then it will be
// overwritten. If the target value is not an object then ErrTargetKeyNotObject
// is returned.
func (e *Event) Put(key string, val *Value) (old *Value, err error) {
return e.put(keyToPath(key), val, true)
}
// TryPut puts a value into the map if the key does not exist. If the key
// already exists it will return the existing value and ErrKeyExists. If the
// target value is not an object then ErrTargetKeyNotObject is returned.
func (e *Event) TryPut(key string, val *Value) (existing *Value, err error) {
return e.put(keyToPath(key), val, false)
}
func (e *Event) put(path []string, val *Value, overwrite bool) (old *Value, err error) {
if len(path) == 0 {
return nil, fmt.Errorf("event put failed: %w", ErrEmptyKey)
}
if val == nil {
return nil, nil
}
if e.fields == nil {
e.init()
}
old = e.get(path)
if old != nil && !overwrite {
return old, fmt.Errorf("event put failed for path <%s>: %w", pathString(path), ErrKeyExists)
}
m := e.fields
for _, key := range path[:len(path)-1] {
inner, found := m[key]
if found {
if inner.Type != ObjectType {
return nil, fmt.Errorf("event put failed for path <%s>: %w", pathString(path), ErrTargetKeyNotObject)
}
m = inner.Object
continue
}
newObj := Object(map[string]*Value{})
m[key] = newObj
m = newObj.Object
}
m[path[len(path)-1]] = val
return old, nil
}
// Get returns the value associated to the given key. It returns nil if the key
// does not exist.
func (e *Event) Get(key string) *Value {
return e.get(keyToPath(key))
}
func (e *Event) get(path []string) *Value {
if len(e.fields) == 0 {
return nil
}
if len(path) == 0 {
// Return root object.
return Object(e.fields)
}
m := e.fields
for _, key := range path[:len(path)-1] {
inner, found := m[key]
if !found || len(inner.Object) == 0 {
return nil
}
m = inner.Object
}
return m[path[len(path)-1]]
}
// Delete removes the given key. It returns the deleted value if it existed.
func (e *Event) Delete(key string) (deleted *Value) {
return e.delete(keyToPath(key))
}
func (e *Event) delete(path []string) (deleted *Value) {
if len(path) == 0 || len(e.fields) == 0 {
return nil
}
v := e.get(path)
if v != nil {
delete(e.fields, path[0])
}
return v
}
func (e *Event) MarshalJSON() ([]byte, error) {
return json.Marshal(e.fields)
}
func (e *Event) UnmarshalJSON(data []byte) error {
var fields map[string]*Value
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
e.fields = fields
return nil
}
// keyToPath creates an object path from a dot-separated key. If a path name
// contains a dot then the dot must be escaped by a backslash.
//
// foo.bar = [foo, bar]
// foo\.bar = [foo.bar]
func keyToPath(key string) []string {
var paths []string
var pathScratch []byte
var escape bool
for i := 0; i < len(key); i++ {
switch c := key[i]; c {
case '\\':
escape = true
case '.':
if escape {
pathScratch = append(pathScratch, '.')
} else {
if len(pathScratch) > 0 {
paths = append(paths, string(pathScratch))
pathScratch = pathScratch[:0]
}
}
escape = false
default:
pathScratch = append(pathScratch, c)
escape = false
}
}
if len(pathScratch) > 0 {
paths = append(paths, string(pathScratch))
}
return paths
}
func pathString(path []string) string {
switch len(path) {
case 0:
return "/"
case 1:
return "/" + path[0]
}
var sb strings.Builder
for _, elem := range path {
sb.WriteByte('/')
sb.WriteString(elem)
}
return sb.String()
}