/
slab.go
52 lines (43 loc) · 1.04 KB
/
slab.go
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
package slab
type slabEntry struct {
Value interface{}
Index uintptr
}
func (entry slabEntry) IsValid() bool {
return entry.Value != nil
}
// Slab is an implementation of the internal registry free list. A zero-value
// instance is a valid instance. This data structure is not thread-safe.
type Slab struct {
entries []slabEntry
free uintptr
}
func (s *Slab) Put(entry interface{}) uintptr {
if s.free == uintptr(len(s.entries)) {
index := uintptr(len(s.entries))
s.entries = append(s.entries, slabEntry{entry, 0})
s.free++
return index
}
index := s.free
s.free = s.entries[index].Index
s.entries[index] = slabEntry{entry, 0}
return index
}
func (s *Slab) Get(i uintptr) interface{} {
// Perform bound check.
if i >= uintptr(len(s.entries)) {
return nil
}
// Perform validity check in case of invalid ID.
if entry := s.entries[i]; entry.IsValid() {
return entry.Value
}
return nil
}
func (s *Slab) Pop(i uintptr) interface{} {
popped := s.entries[i].Value
s.entries[i] = slabEntry{nil, s.free}
s.free = i
return popped
}