File: element.go

package info (click to toggle)
golang-k8s-sigs-structured-merge-diff 6.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 2,608 kB
  • sloc: sh: 105; makefile: 4
file content (388 lines) | stat: -rw-r--r-- 10,181 bytes parent folder | download
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
Copyright 2018 The Kubernetes Authors.

Licensed 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 fieldpath

import (
	"fmt"
	"iter"
	"sort"
	"strings"

	"sigs.k8s.io/structured-merge-diff/v6/value"
)

// PathElement describes how to select a child field given a containing object.
type PathElement struct {
	// Exactly one of the following fields should be non-nil.

	// FieldName selects a single field from a map (reminder: this is also
	// how structs are represented). The containing object must be a map.
	FieldName *string

	// Key selects the list element which has fields matching those given.
	// The containing object must be an associative list with map typed
	// elements. They are sorted alphabetically.
	Key *value.FieldList

	// Value selects the list element with the given value. The containing
	// object must be an associative list with a primitive typed element
	// (i.e., a set).
	Value *value.Value

	// Index selects a list element by its index number. The containing
	// object must be an atomic list.
	Index *int
}

// FieldNameElement creates a new FieldName PathElement.
func FieldNameElement(name string) PathElement {
	return PathElement{FieldName: &name}
}

// KeyElement creates a new Key PathElement with the key fields.
func KeyElement(fields ...value.Field) PathElement {
	l := value.FieldList(fields)
	return PathElement{Key: &l}
}

// KeyElementByFields creates a new Key PathElement from names and values.
// `nameValues` must have an even number of entries, alternating
// names (type must be string) with values (type must be value.Value). If these
// conditions are not met, KeyByFields will panic--it's intended for static
// construction and shouldn't have user-produced values passed to it.
func KeyElementByFields(nameValues ...any) PathElement {
	return PathElement{Key: KeyByFields(nameValues...)}
}

// ValueElement creates a new Value PathElement.
func ValueElement(value value.Value) PathElement {
	return PathElement{Value: &value}
}

// IndexElement creates a new Index PathElement.
func IndexElement(index int) PathElement {
	return PathElement{Index: &index}
}

// Less provides an order for path elements.
func (e PathElement) Less(rhs PathElement) bool {
	return e.Compare(rhs) < 0
}

// Compare provides an order for path elements.
func (e PathElement) Compare(rhs PathElement) int {
	if e.FieldName != nil {
		if rhs.FieldName == nil {
			return -1
		}
		return strings.Compare(*e.FieldName, *rhs.FieldName)
	} else if rhs.FieldName != nil {
		return 1
	}

	if e.Key != nil {
		if rhs.Key == nil {
			return -1
		}
		return e.Key.Compare(*rhs.Key)
	} else if rhs.Key != nil {
		return 1
	}

	if e.Value != nil {
		if rhs.Value == nil {
			return -1
		}
		return value.Compare(*e.Value, *rhs.Value)
	} else if rhs.Value != nil {
		return 1
	}

	if e.Index != nil {
		if rhs.Index == nil {
			return -1
		}
		if *e.Index < *rhs.Index {
			return -1
		} else if *e.Index == *rhs.Index {
			return 0
		}
		return 1
	} else if rhs.Index != nil {
		return 1
	}

	return 0
}

// Equals returns true if both path elements are equal.
func (e PathElement) Equals(rhs PathElement) bool {
	if e.FieldName != nil {
		if rhs.FieldName == nil {
			return false
		}
		return *e.FieldName == *rhs.FieldName
	} else if rhs.FieldName != nil {
		return false
	}
	if e.Key != nil {
		if rhs.Key == nil {
			return false
		}
		return e.Key.Equals(*rhs.Key)
	} else if rhs.Key != nil {
		return false
	}
	if e.Value != nil {
		if rhs.Value == nil {
			return false
		}
		return value.Equals(*e.Value, *rhs.Value)
	} else if rhs.Value != nil {
		return false
	}
	if e.Index != nil {
		if rhs.Index == nil {
			return false
		}
		return *e.Index == *rhs.Index
	} else if rhs.Index != nil {
		return false
	}
	return true
}

// String presents the path element as a human-readable string.
func (e PathElement) String() string {
	switch {
	case e.FieldName != nil:
		return "." + *e.FieldName
	case e.Key != nil:
		strs := make([]string, len(*e.Key))
		for i, k := range *e.Key {
			strs[i] = fmt.Sprintf("%v=%v", k.Name, value.ToString(k.Value))
		}
		// Keys are supposed to be sorted.
		return "[" + strings.Join(strs, ",") + "]"
	case e.Value != nil:
		return fmt.Sprintf("[=%v]", value.ToString(*e.Value))
	case e.Index != nil:
		return fmt.Sprintf("[%v]", *e.Index)
	default:
		return "{{invalid path element}}"
	}
}

// Copy returns a copy of the PathElement.
// This is not a full deep copy as any contained value.Value is not copied.
func (e PathElement) Copy() PathElement {
	if e.FieldName != nil {
		return PathElement{FieldName: e.FieldName}
	}
	if e.Key != nil {
		c := e.Key.Copy()
		return PathElement{Key: &c}
	}
	if e.Value != nil {
		return PathElement{Value: e.Value}
	}
	if e.Index != nil {
		return PathElement{Index: e.Index}
	}
	return e // zero value
}

// KeyByFields is a helper function which constructs a key for an associative
// list type. `nameValues` must have an even number of entries, alternating
// names (type must be string) with values (type must be value.Value). If these
// conditions are not met, KeyByFields will panic--it's intended for static
// construction and shouldn't have user-produced values passed to it.
func KeyByFields(nameValues ...interface{}) *value.FieldList {
	if len(nameValues)%2 != 0 {
		panic("must have a value for every name")
	}
	out := value.FieldList{}
	for i := 0; i < len(nameValues)-1; i += 2 {
		out = append(out, value.Field{Name: nameValues[i].(string), Value: value.NewValueInterface(nameValues[i+1])})
	}
	out.Sort()
	return &out
}

// PathElementSet is a set of path elements.
// TODO: serialize as a list.
type PathElementSet struct {
	members sortedPathElements
}

func MakePathElementSet(size int) PathElementSet {
	return PathElementSet{
		members: make(sortedPathElements, 0, size),
	}
}

type sortedPathElements []PathElement

// Implement the sort interface; this would permit bulk creation, which would
// be faster than doing it one at a time via Insert.
func (spe sortedPathElements) Len() int           { return len(spe) }
func (spe sortedPathElements) Less(i, j int) bool { return spe[i].Less(spe[j]) }
func (spe sortedPathElements) Swap(i, j int)      { spe[i], spe[j] = spe[j], spe[i] }

// Copy returns a copy of the PathElementSet.
// This is not a full deep copy as any contained value.Value is not copied.
func (s PathElementSet) Copy() PathElementSet {
	out := make(sortedPathElements, len(s.members))
	for i := range s.members {
		out[i] = s.members[i].Copy()
	}
	return PathElementSet{members: out}
}

// Insert adds pe to the set.
func (s *PathElementSet) Insert(pe PathElement) {
	loc := sort.Search(len(s.members), func(i int) bool {
		return !s.members[i].Less(pe)
	})
	if loc == len(s.members) {
		s.members = append(s.members, pe)
		return
	}
	if s.members[loc].Equals(pe) {
		return
	}
	s.members = append(s.members, PathElement{})
	copy(s.members[loc+1:], s.members[loc:])
	s.members[loc] = pe
}

// Union returns a set containing elements that appear in either s or s2.
func (s *PathElementSet) Union(s2 *PathElementSet) *PathElementSet {
	out := &PathElementSet{}

	i, j := 0, 0
	for i < len(s.members) && j < len(s2.members) {
		if s.members[i].Less(s2.members[j]) {
			out.members = append(out.members, s.members[i])
			i++
		} else {
			out.members = append(out.members, s2.members[j])
			if !s2.members[j].Less(s.members[i]) {
				i++
			}
			j++
		}
	}

	if i < len(s.members) {
		out.members = append(out.members, s.members[i:]...)
	}
	if j < len(s2.members) {
		out.members = append(out.members, s2.members[j:]...)
	}
	return out
}

// Intersection returns a set containing elements which appear in both s and s2.
func (s *PathElementSet) Intersection(s2 *PathElementSet) *PathElementSet {
	out := &PathElementSet{}

	i, j := 0, 0
	for i < len(s.members) && j < len(s2.members) {
		if s.members[i].Less(s2.members[j]) {
			i++
		} else {
			if !s2.members[j].Less(s.members[i]) {
				out.members = append(out.members, s.members[i])
				i++
			}
			j++
		}
	}

	return out
}

// Difference returns a set containing elements which appear in s but not in s2.
func (s *PathElementSet) Difference(s2 *PathElementSet) *PathElementSet {
	out := &PathElementSet{}

	i, j := 0, 0
	for i < len(s.members) && j < len(s2.members) {
		if s.members[i].Less(s2.members[j]) {
			out.members = append(out.members, s.members[i])
			i++
		} else {
			if !s2.members[j].Less(s.members[i]) {
				i++
			}
			j++
		}
	}
	if i < len(s.members) {
		out.members = append(out.members, s.members[i:]...)
	}
	return out
}

// Size retuns the number of elements in the set.
func (s *PathElementSet) Size() int { return len(s.members) }

// Has returns true if pe is a member of the set.
func (s *PathElementSet) Has(pe PathElement) bool {
	loc := sort.Search(len(s.members), func(i int) bool {
		return !s.members[i].Less(pe)
	})
	if loc == len(s.members) {
		return false
	}
	if s.members[loc].Equals(pe) {
		return true
	}
	return false
}

// Equals returns true if s and s2 have exactly the same members.
func (s *PathElementSet) Equals(s2 *PathElementSet) bool {
	if len(s.members) != len(s2.members) {
		return false
	}
	for k := range s.members {
		if !s.members[k].Equals(s2.members[k]) {
			return false
		}
	}
	return true
}

// Iterate calls f for each PathElement in the set. The order is deterministic.
func (s *PathElementSet) Iterate(f func(PathElement)) {
	for _, pe := range s.members {
		f(pe)
	}
}

// All iterates over each PathElement in the set. The order is deterministic.
func (s *PathElementSet) All() iter.Seq[PathElement] {
	return func(yield func(element PathElement) bool) {
		for _, pe := range s.members {
			if !yield(pe) {
				return
			}
		}
	}
}