summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-structr/queue.go
blob: 1e735762f742b9672aa6a6b6f80541354c17bea5 (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
package structr

import (
	"reflect"
	"sync"
	"unsafe"
)

// QueueConfig defines config vars
// for initializing a struct queue.
type QueueConfig[StructType any] struct {

	// Indices defines indices to create
	// in the Queue for the receiving
	// generic struct parameter type.
	Indices []IndexConfig

	// Pop is called when queue values
	// are popped, during calls to any
	// of the Pop___() series of fns.
	Pop func(StructType)
}

// Queue provides a structure model queue with
// automated indexing and popping by any init
// defined lookups of field combinations.
type Queue[StructType any] struct {

	// indices used in storing passed struct
	// types by user defined sets of fields.
	indices []Index

	// main underlying
	// struct item queue.
	queue list

	// hook functions.
	copy func(StructType) StructType
	pop  func(StructType)

	// protective mutex, guards:
	// - Queue{}.queue
	// - Index{}.data
	// - Queue{} hook fns
	mutex sync.Mutex
}

// Init initializes the queue with given configuration
// including struct fields to index, and necessary fns.
func (q *Queue[T]) Init(config QueueConfig[T]) {
	t := reflect.TypeOf((*T)(nil)).Elem()

	if len(config.Indices) == 0 {
		panic("no indices provided")
	}

	// Safely copy over
	// provided config.
	q.mutex.Lock()
	q.indices = make([]Index, len(config.Indices))
	for i, cfg := range config.Indices {
		q.indices[i].ptr = unsafe.Pointer(q)
		q.indices[i].init(t, cfg, 0)
	}
	q.pop = config.Pop
	q.mutex.Unlock()
}

// Index selects index with given name from queue, else panics.
func (q *Queue[T]) Index(name string) *Index {
	for i := range q.indices {
		if q.indices[i].name == name {
			return &q.indices[i]
		}
	}
	panic("unknown index: " + name)
}

// PopFront pops the current value at front of the queue.
func (q *Queue[T]) PopFront() (T, bool) {
	t := q.PopFrontN(1)
	if len(t) == 0 {
		var t T
		return t, false
	}
	return t[0], true
}

// PopBack pops the current value at back of the queue.
func (q *Queue[T]) PopBack() (T, bool) {
	t := q.PopBackN(1)
	if len(t) == 0 {
		var t T
		return t, false
	}
	return t[0], true
}

// PopFrontN attempts to pop n values from front of the queue.
func (q *Queue[T]) PopFrontN(n int) []T {
	return q.pop_n(n, func() *list_elem {
		return q.queue.head
	})
}

// PopBackN attempts to pop n values from back of the queue.
func (q *Queue[T]) PopBackN(n int) []T {
	return q.pop_n(n, func() *list_elem {
		return q.queue.tail
	})
}

// Pop attempts to pop values from queue indexed under any of keys.
func (q *Queue[T]) Pop(index *Index, keys ...Key) []T {
	if index == nil {
		panic("no index given")
	} else if index.ptr != unsafe.Pointer(q) {
		panic("invalid index for queue")
	}

	// Acquire lock.
	q.mutex.Lock()

	// Preallocate expected ret slice.
	values := make([]T, 0, len(keys))

	for i := range keys {
		// Delete all items under key from index, collecting
		// value items and dropping them from all their indices.
		index.delete(keys[i], func(item *indexed_item) {

			// Append deleted to values.
			value := item.data.(T)
			values = append(values, value)

			// Delete queued.
			q.delete(item)
		})
	}

	// Get func ptrs.
	pop := q.pop

	// Done with lock.
	q.mutex.Unlock()

	if pop != nil {
		// Pass all popped values
		// to given user hook (if set).
		for _, value := range values {
			pop(value)
		}
	}

	return values
}

// PushFront pushes values to front of queue.
func (q *Queue[T]) PushFront(values ...T) {
	q.mutex.Lock()
	for i := range values {
		item := q.index(values[i])
		q.queue.push_front(&item.elem)
	}
	q.mutex.Unlock()
}

// PushBack pushes values to back of queue.
func (q *Queue[T]) PushBack(values ...T) {
	q.mutex.Lock()
	for i := range values {
		item := q.index(values[i])
		q.queue.push_back(&item.elem)
	}
	q.mutex.Unlock()
}

// MoveFront attempts to move values indexed under any of keys to the front of the queue.
func (q *Queue[T]) MoveFront(index *Index, keys ...Key) {
	q.mutex.Lock()
	for i := range keys {
		index.get(keys[i], func(item *indexed_item) {
			q.queue.move_front(&item.elem)
		})
	}
	q.mutex.Unlock()
}

// MoveBack attempts to move values indexed under any of keys to the back of the queue.
func (q *Queue[T]) MoveBack(index *Index, keys ...Key) {
	q.mutex.Lock()
	for i := range keys {
		index.get(keys[i], func(item *indexed_item) {
			q.queue.move_back(&item.elem)
		})
	}
	q.mutex.Unlock()
}

// Len returns the current length of queue.
func (q *Queue[T]) Len() int {
	q.mutex.Lock()
	l := q.queue.len
	q.mutex.Unlock()
	return l
}

func (q *Queue[T]) pop_n(n int, next func() *list_elem) []T {
	if next == nil {
		panic("nil fn")
	}

	// Acquire lock.
	q.mutex.Lock()

	// Preallocate ret slice.
	values := make([]T, 0, n)

	// Iterate over 'n' items.
	for i := 0; i < n; i++ {

		// Get next elem.
		next := next()
		if next == nil {

			// reached
			// end.
			break
		}

		// Cast the indexed item from elem.
		item := (*indexed_item)(next.data)

		// Append deleted to values.
		value := item.data.(T)
		values = append(values, value)

		// Delete queued.
		q.delete(item)
	}

	// Get func ptrs.
	pop := q.pop

	// Done with lock.
	q.mutex.Unlock()

	if pop != nil {
		// Pass all popped values
		// to given user hook (if set).
		for _, value := range values {
			pop(value)
		}
	}

	return values
}

func (q *Queue[T]) index(value T) *indexed_item {
	item := new_indexed_item()

	// Set item value.
	item.data = value

	// Acquire key buf.
	buf := new_buffer()

	for i := range q.indices {
		// Get current index ptr.
		idx := &(q.indices[i])

		// Extract fields comprising index key.
		parts := extract_fields(value, idx.fields)

		// Calculate index key.
		key := idx.key(buf, parts)
		if key.Zero() {
			continue
		}

		// Append item to index.
		idx.append(key, item)
	}

	// Done with buf.
	free_buffer(buf)

	return item
}

func (q *Queue[T]) delete(item *indexed_item) {
	for len(item.indexed) != 0 {
		// Pop last indexed entry from list.
		entry := item.indexed[len(item.indexed)-1]
		item.indexed = item.indexed[:len(item.indexed)-1]

		// Drop index_entry from index.
		entry.index.delete_entry(entry)
	}

	// Drop entry from queue list.
	q.queue.remove(&item.elem)

	// Free now-unused item.
	free_indexed_item(item)
}