summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-structr/index.go
blob: b8f6b9d01777c95712e764196cb04e55fcb554dc (plain)
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package structr

import (
	"reflect"
	"strings"
	"sync"
	"unsafe"

	"codeberg.org/gruf/go-byteutil"
)

// IndexConfig defines config variables
// for initializing a struct index.
type IndexConfig struct {

	// Fields should contain a comma-separated
	// list of struct fields used when generating
	// keys for this index. Nested fields should
	// be specified using periods. An example:
	// "Username,Favorites.Color"
	//
	// Note that nested fields where the nested
	// struct field is a ptr are supported, but
	// nil ptr values in nesting will result in
	// that particular value NOT being indexed.
	// e.g. with "Favorites.Color" if *Favorites
	// is nil then it will not be indexed.
	//
	// Field types supported include any of those
	// supported by the `go-mangler` library.
	Fields string

	// Multiple indicates whether to accept multiple
	// possible values for any single index key. The
	// default behaviour is to only accept one value
	// and overwrite existing on any write operation.
	Multiple bool

	// AllowZero indicates whether to accept zero
	// value fields in index keys. i.e. whether to
	// index structs for this set of field values
	// IF any one of those field values is the zero
	// value for that type. The default behaviour
	// is to skip indexing structs for this lookup
	// when any of the indexing fields are zero.
	AllowZero bool
}

// Index is an exposed Cache internal model, used to
// extract struct keys, generate hash checksums for them
// and store struct results by the init defined config.
// This model is exposed to provide faster lookups in the
// case that you would like to manually provide the used
// index via the Cache.___By() series of functions, or
// access the underlying index key generator.
type Index struct {

	// ptr is a pointer to
	// the source Cache/Queue
	// index is attached to.
	ptr unsafe.Pointer

	// name is the actual name of this
	// index, which is the unparsed
	// string value of contained fields.
	name string

	// backing data store of the index, containing
	// the cached results contained within wrapping
	// index_entry{} which also contains the exact
	// key each result is stored under. the hash map
	// only keys by the xxh3 hash checksum for speed.
	data map[string]*list // [*index_entry]

	// struct fields encompassed by
	// keys (+ hashes) of this index.
	fields []struct_field

	// index flags:
	// - 1 << 0 = unique
	// - 1 << 1 = allow zero
	flags uint8
}

// Name returns the receiving Index name.
func (i *Index) Name() string {
	return i.name
}

// Key generates Key{} from given parts for
// the type of lookup this Index uses in cache.
// NOTE: panics on incorrect no. parts / types given.
func (i *Index) Key(parts ...any) Key {
	buf := new_buffer()
	key := i.key(buf, parts)
	free_buffer(buf)
	return key
}

// Keys generates []Key{} from given (multiple) parts
// for the type of lookup this Index uses in the cache.
// NOTE: panics on incorrect no. parts / types given.
func (i *Index) Keys(parts ...[]any) []Key {
	keys := make([]Key, 0, len(parts))
	buf := new_buffer()
	for _, parts := range parts {
		key := i.key(buf, parts)
		if key.Zero() {
			continue
		}
		keys = append(keys, key)
	}
	free_buffer(buf)
	return keys
}

// init will initialize the cache with given type, config and capacity.
func (i *Index) init(t reflect.Type, cfg IndexConfig, cap int) {
	switch {
	// The only 2 types we support are
	// structs, and ptrs to a struct.
	case t.Kind() == reflect.Struct:
	case t.Kind() == reflect.Pointer &&
		t.Elem().Kind() == reflect.Struct:
	default:
		panic("index only support struct{} and *struct{}")
	}

	// Set name from the raw
	// struct fields string.
	i.name = cfg.Fields

	// Set struct flags.
	if cfg.AllowZero {
		set_allow_zero(&i.flags)
	}
	if !cfg.Multiple {
		set_is_unique(&i.flags)
	}

	// Split to get containing struct fields.
	fields := strings.Split(cfg.Fields, ",")

	// Preallocate expected struct field slice.
	i.fields = make([]struct_field, len(fields))
	for x, name := range fields {

		// Split name to account for nesting.
		names := strings.Split(name, ".")

		// Look for usable struct field.
		i.fields[x] = find_field(t, names)
	}

	// Initialize index_entry list store.
	i.data = make(map[string]*list, cap+1)
}

// get_one will fetch one indexed item under key.
func (i *Index) get_one(key Key) *indexed_item {
	// Get list at hash.
	l := i.data[key.key]
	if l == nil {
		return nil
	}

	// Extract entry from first list elem.
	entry := (*index_entry)(l.head.data)

	// Check contains expected key.
	if !entry.key.Equal(key) {
		return nil
	}

	return entry.item
}

// get will fetch all indexed items under key, passing each to hook.
func (i *Index) get(key Key, hook func(*indexed_item)) {
	if hook == nil {
		panic("nil hook")
	}

	// Get list at hash.
	l := i.data[key.key]
	if l == nil {
		return
	}

	// Extract entry from first list elem.
	entry := (*index_entry)(l.head.data)

	// Check contains expected key.
	if !entry.key.Equal(key) {
		return
	}

	// Iterate all entries in list.
	l.rangefn(func(elem *list_elem) {

		// Extract element entry + item.
		entry := (*index_entry)(elem.data)
		item := entry.item

		// Pass to hook.
		hook(item)
	})
}

// key uses hasher to generate Key{} from given raw parts.
func (i *Index) key(buf *byteutil.Buffer, parts []any) Key {
	if len(parts) != len(i.fields) {
		panicf("incorrect number key parts: want=%d received=%d",
			len(i.fields),
			len(parts),
		)
	}
	buf.B = buf.B[:0]
	if !allow_zero(i.flags) {
		for x, field := range i.fields {
			before := len(buf.B)
			buf.B = field.mangle(buf.B, parts[x])
			if string(buf.B[before:]) == field.zero {
				return Key{}
			}
			buf.B = append(buf.B, '.')
		}
	} else {
		for x, field := range i.fields {
			buf.B = field.mangle(buf.B, parts[x])
			buf.B = append(buf.B, '.')
		}
	}
	return Key{
		raw: parts,
		key: string(buf.B),
	}
}

// append will append the given index entry to appropriate
// doubly-linked-list in index hashmap. this handles case
// of key collisions and overwriting 'unique' entries.
func (i *Index) append(key Key, item *indexed_item) {
	// Look for existing.
	l := i.data[key.key]

	if l == nil {

		// Allocate new.
		l = new_list()
		i.data[key.key] = l

	} else if is_unique(i.flags) {

		// Remove head.
		elem := l.head
		l.remove(elem)

		// Drop index from inner item.
		e := (*index_entry)(elem.data)
		e.item.drop_index(e)

		// Free unused entry.
		free_index_entry(e)
	}

	// Prepare new index entry.
	entry := new_index_entry()
	entry.item = item
	entry.key = key
	entry.index = i

	// Add ourselves to item's index tracker.
	item.indexed = append(item.indexed, entry)

	// Add entry to index list.
	l.push_front(&entry.elem)
}

// delete will remove all indexed items under key, passing each to hook.
func (i *Index) delete(key Key, hook func(*indexed_item)) {
	if hook == nil {
		panic("nil hook")
	}

	// Get list at hash.
	l := i.data[key.key]
	if l == nil {
		return
	}

	// Extract entry from first list elem.
	entry := (*index_entry)(l.head.data)

	// Check contains expected key.
	if !entry.key.Equal(key) {
		return
	}

	// Delete data at hash.
	delete(i.data, key.key)

	// Iterate entries in list.
	for x := 0; x < l.len; x++ {

		// Pop list head.
		elem := l.head
		l.remove(elem)

		// Extract element entry + item.
		entry := (*index_entry)(elem.data)
		item := entry.item

		// Drop index from item.
		item.drop_index(entry)

		// Free now-unused entry.
		free_index_entry(entry)

		// Pass to hook.
		hook(item)
	}

	// Release list.
	free_list(l)
}

// delete_entry deletes the given index entry.
func (i *Index) delete_entry(entry *index_entry) {
	// Get list at hash sum.
	l := i.data[entry.key.key]
	if l == nil {
		return
	}

	// Remove list entry.
	l.remove(&entry.elem)

	if l.len == 0 {
		// Remove entry list from map.
		delete(i.data, entry.key.key)

		// Release list.
		free_list(l)
	}

	// Drop this index from item.
	entry.item.drop_index(entry)
}

// index_entry represents a single entry
// in an Index{}, where it will be accessible
// by Key{} pointing to a containing list{}.
type index_entry struct {

	// list elem that entry is stored
	// within, under containing index.
	// elem.data is ptr to index_entry.
	elem list_elem

	// hash checksum
	// + raw key data
	key Key

	// index this is stored in.
	index *Index

	// underlying indexed item.
	item *indexed_item
}

var index_entry_pool sync.Pool

// new_index_entry returns a new prepared index_entry.
func new_index_entry() *index_entry {
	v := index_entry_pool.Get()
	if v == nil {
		v = new(index_entry)
	}
	entry := v.(*index_entry)
	ptr := unsafe.Pointer(entry)
	entry.elem.data = ptr
	return entry
}

// free_index_entry releases the index_entry.
func free_index_entry(entry *index_entry) {
	entry.elem.data = nil
	entry.key = Key{}
	entry.index = nil
	entry.item = nil
	index_entry_pool.Put(entry)
}

func is_unique(f uint8) bool {
	const mask = uint8(1) << 0
	return f&mask != 0
}

func set_is_unique(f *uint8) {
	const mask = uint8(1) << 0
	(*f) |= mask
}

func allow_zero(f uint8) bool {
	const mask = uint8(1) << 1
	return f&mask != 0
}

func set_allow_zero(f *uint8) {
	const mask = uint8(1) << 1
	(*f) |= mask
}