summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-structr/result.go
blob: 08d3ad013e104abc464b43e8ca73d0dd5597d0e5 (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
package structr

import (
	"sync"
	"unsafe"
)

var result_pool sync.Pool

type result struct {
	// linked list elem this result is
	// stored under in Cache.lruList.
	elem list_elem

	// indexed stores the indices
	// this result is stored under.
	indexed []*index_entry

	// cached data (we maintain
	// the type data here using
	// an interface as any one
	// instance can be T / error).
	data interface{}
}

func result_acquire[T any](c *Cache[T]) *result {
	// Acquire from pool.
	v := result_pool.Get()
	if v == nil {
		v = new(result)
	}

	// Cast result value.
	res := v.(*result)

	// Push result elem to front of LRU list.
	list_push_front(&c.lruList, &res.elem)
	res.elem.data = unsafe.Pointer(res)

	return res
}

func result_release[T any](c *Cache[T], res *result) {
	// Remove result elem from LRU list.
	list_remove(&c.lruList, &res.elem)
	res.elem.data = nil

	// Reset all result fields.
	res.indexed = res.indexed[:0]
	res.data = nil

	// Release to pool.
	result_pool.Put(res)
}

func result_drop_index[T any](res *result, index *Index[T]) {
	for i := 0; i < len(res.indexed); i++ {

		if res.indexed[i].index != unsafe.Pointer(index) {
			// Prof. Obiwan:
			// this is not the index
			// we are looking for.
			continue
		}

		// Get index entry ptr.
		entry := res.indexed[i]

		// Move all index entries down + reslice.
		copy(res.indexed[i:], res.indexed[i+1:])
		res.indexed = res.indexed[:len(res.indexed)-1]

		// Release to memory pool.
		index_entry_release(entry)

		return
	}
}