| 1 |
|
| 2 |
|
| 3 |
package memory |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"math" |
| 8 |
"sync" |
| 9 |
|
| 10 |
"golang.org/x/sys/unix" |
| 11 |
) |
| 12 |
|
| 13 |
type Memory struct { |
| 14 |
Buf []byte |
| 15 |
Max int64 |
| 16 |
com int |
| 17 |
mu sync.Mutex |
| 18 |
} |
| 19 |
|
| 20 |
func (m *Memory) Slice() *[]byte { |
| 21 |
return &m.Buf |
| 22 |
} |
| 23 |
|
| 24 |
func (m *Memory) Grow(delta, _ int64) int64 { |
| 25 |
m.mu.Lock() |
| 26 |
defer m.mu.Unlock() |
| 27 |
|
| 28 |
if m.Buf == nil { |
| 29 |
m.allocate(uint64(m.Max) << 16) |
| 30 |
} |
| 31 |
|
| 32 |
sz := len(m.Buf) |
| 33 |
old := int64(sz >> 16) |
| 34 |
if delta == 0 { |
| 35 |
return old |
| 36 |
} |
| 37 |
newPages := old + delta |
| 38 |
if newPages > m.Max { |
| 39 |
return -1 |
| 40 |
} |
| 41 |
m.reallocate(uint64(newPages) << 16) |
| 42 |
return old |
| 43 |
} |
| 44 |
|
| 45 |
func (m *Memory) allocate(maxSz uint64) { |
| 46 |
|
| 47 |
rnd := uint64(unix.Getpagesize() - 1) |
| 48 |
res := (maxSz + rnd) &^ rnd |
| 49 |
|
| 50 |
if res > math.MaxInt { |
| 51 |
|
| 52 |
|
| 53 |
res = math.MaxUint64 |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
b, err := unix.Mmap(-1, 0, int(res), unix.PROT_NONE, unix.MAP_PRIVATE|unix.MAP_ANON) |
| 59 |
if err != nil { |
| 60 |
panic(err) |
| 61 |
} |
| 62 |
m.Buf = b[:0] |
| 63 |
} |
| 64 |
|
| 65 |
func (m *Memory) reallocate(size uint64) { |
| 66 |
com := uint64(m.com) |
| 67 |
res := uint64(cap(m.Buf)) |
| 68 |
if com < size && size <= res { |
| 69 |
|
| 70 |
rnd := uint64(unix.Getpagesize() - 1) |
| 71 |
newSz := com + com>>3 |
| 72 |
newSz = min(max(size, newSz), res) |
| 73 |
newSz = (newSz + rnd) &^ rnd |
| 74 |
|
| 75 |
|
| 76 |
err := unix.Mprotect(m.Buf[m.com:newSz], unix.PROT_READ|unix.PROT_WRITE) |
| 77 |
if err != nil { |
| 78 |
panic(err) |
| 79 |
} |
| 80 |
m.com = int(newSz) |
| 81 |
} |
| 82 |
buf := m.Buf[:size] |
| 83 |
atomicStoreSliceLen(&m.Buf, len(buf)) |
| 84 |
} |
| 85 |
|
| 86 |
func (m *Memory) Close() error { |
| 87 |
m.mu.Lock() |
| 88 |
defer m.mu.Unlock() |
| 89 |
|
| 90 |
err := unix.Munmap(m.Buf[:cap(m.Buf)]) |
| 91 |
m.Buf = nil |
| 92 |
m.com = 0 |
| 93 |
return fmt.Errorf("memory: unmap failed: %w", err) |
| 94 |
} |