summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-mempool/pool.go
blob: e5ff6ba3dc2102090f18838a9b315423d97b424b (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
package mempool

import (
	"unsafe"
)

const DefaultDirtyFactor = 128

// Pool provides a type-safe form
// of UnsafePool using generics.
//
// Note it is NOT safe for concurrent
// use, you must protect it yourself!
type Pool[T any] struct {

	// New is an optionally provided
	// allocator used when no value
	// is available for use in pool.
	New func() T

	// Reset is an optionally provided
	// value resetting function called
	// on passed value to Put().
	Reset func(T)

	UnsafePool
}

func (p *Pool[T]) Get() T {
	if ptr := p.UnsafePool.Get(); ptr != nil {
		return *(*T)(ptr)
	} else if p.New != nil {
		return p.New()
	}
	var z T
	return z
}

func (p *Pool[T]) Put(t T) {
	if p.Reset != nil {
		p.Reset(t)
	}
	ptr := unsafe.Pointer(&t)
	p.UnsafePool.Put(ptr)
}

// UnsafePool provides an incredibly
// simple memory pool implementation
// that stores ptrs to memory values,
// and regularly flushes internal pool
// structures according to DirtyFactor.
//
// Note it is NOT safe for concurrent
// use, you must protect it yourself!
type UnsafePool struct {

	// DirtyFactor determines the max
	// number of $dirty count before
	// pool is garbage collected. Where:
	// $dirty = len(current) - len(victim)
	DirtyFactor int

	current []unsafe.Pointer
	victim  []unsafe.Pointer
}

func (p *UnsafePool) Get() unsafe.Pointer {
	// First try current list.
	if len(p.current) > 0 {
		ptr := p.current[len(p.current)-1]
		p.current = p.current[:len(p.current)-1]
		return ptr
	}

	// Fallback to victim.
	if len(p.victim) > 0 {
		ptr := p.victim[len(p.victim)-1]
		p.victim = p.victim[:len(p.victim)-1]
		return ptr
	}

	return nil
}

func (p *UnsafePool) Put(ptr unsafe.Pointer) {
	p.current = append(p.current, ptr)

	// Get dirty factor.
	df := p.DirtyFactor
	if df == 0 {
		df = DefaultDirtyFactor
	}

	if len(p.current)-len(p.victim) > df {
		// Garbage collection!
		p.victim = p.current
		p.current = nil
	}
}