-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.go
More file actions
68 lines (58 loc) · 1.34 KB
/
memory.go
File metadata and controls
68 lines (58 loc) · 1.34 KB
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
package alchemist
import (
"sync"
"sync/atomic"
)
const arenaShards = 256
type PointerArena[T any] struct {
shards [arenaShards]*shard[T]
counter atomic.Uintptr
}
type shard[T any] struct {
mu sync.Mutex
m sync.Map // map[uintptr]*AlchemistValue[T]
}
func NewPointerArena[T any]() *PointerArena[T] {
arena := &PointerArena[T]{}
for i := 0; i < arenaShards; i++ {
arena.shards[i] = &shard[T]{}
}
return arena
}
func (a *PointerArena[T]) shard(uid uintptr) *shard[T] {
return a.shards[uid%arenaShards]
}
// Alloc возвращает уникальный UID и записывает объект
func (a *PointerArena[T]) alloc(obj *AlchemistValue[T]) uintptr {
uid := a.counter.Add(1)
obj.setUIDValue(uid)
s := a.shard(uid)
s.mu.Lock()
s.m.Store(uid, obj)
s.mu.Unlock()
return uid
}
// Get возвращает объект по UID, lock-free
func (a *PointerArena[T]) Get(uid uintptr) *AlchemistValue[T] {
s := a.shard(uid)
if v, ok := s.m.Load(uid); ok {
return v.(*AlchemistValue[T])
}
return nil
}
// Free удаляет объект
func (a *PointerArena[T]) free(uid uintptr) {
s := a.shard(uid)
s.mu.Lock()
s.m.Delete(uid)
s.mu.Unlock()
}
// Destroy очищает все данные
func (a *PointerArena[T]) destroy() {
for _, s := range a.shards {
s.mu.Lock()
s.m = sync.Map{}
s.mu.Unlock()
}
a.counter.Store(0)
}