github.com/moontrade/nogc@v0.1.7/alloc/tlsf/arena_slice.go (about) 1 //go:build !tinygo && !wasm && !wasi && !tinygo.wasm 2 // +build !tinygo,!wasm,!wasi,!tinygo.wasm 3 4 package tlsf 5 6 import ( 7 "sync" 8 "unsafe" 9 ) 10 11 var ( 12 allocators map[unsafe.Pointer]Arena 13 allocatorsMu sync.Mutex 14 ) 15 16 // SliceArena allocates memory by creating Go byte slices 17 type SliceArena struct { 18 allocs map[uintptr][]byte 19 } 20 21 func NewSliceArena() *SliceArena { 22 // Allocate on Go GC 23 a := &SliceArena{ 24 allocs: make(map[uintptr][]byte, 16), 25 } 26 allocatorsMu.Lock() 27 if allocators == nil { 28 allocators = make(map[unsafe.Pointer]Arena) 29 } 30 allocators[unsafe.Pointer(a)] = a 31 allocatorsMu.Unlock() 32 return a 33 } 34 35 func (a *SliceArena) Alloc(size uintptr) (uintptr, uintptr) { 36 b := make([]byte, size) 37 p := unsafe.Pointer(&b[0]) 38 a.allocs[uintptr(p)] = b 39 return uintptr(p), uintptr(p) + uintptr(cap(b)) 40 } 41 42 func (a *SliceArena) Free() { 43 allocatorsMu.Lock() 44 defer allocatorsMu.Unlock() 45 // Clear all allocs to help GC marking 46 for k := range a.allocs { 47 delete(a.allocs, k) 48 } 49 // Remove from global allocators map and the GC will free when needed 50 delete(allocators, unsafe.Pointer(a)) 51 }