Skip to content

Commit

Permalink
chore(mempool): better comment
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaost committed Aug 21, 2024
1 parent 1a8a7b3 commit 11d91db
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
21 changes: 13 additions & 8 deletions cache/mempool/mempool.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,20 @@ const (
)

const (
// footer is a [8]byte, it contains two parts: magic(58 bits) and index (6 bits)
// footer is a [8]byte, it contains two parts: magic(58 bits) and index (6 bits):
// * magic is for checking a []byte is created by this package
// * index is for `pools`, the cap of a []byte is always equal to pools[i].Size
// we use footer instead of header to ensure that `Free` is always safe regardless of the input provided.
footerLen = 8

footerMagicMask = uint64(0xFFFFFFFFFFFFFFC0) // 58 bits mask for `footerMagic`
footerIndexMask = uint64(0x000000000000003F) // 6 bits mask, [0, 63], for `pools`, `bits2idx`
footerMagic = uint64(0xBADC0DEBADC0DEC0) // uint64 ends with 6 zero bits
footerMagicMask = uint64(0xFFFFFFFFFFFFFFC0) // 58 bits mask
footerIndexMask = uint64(0x000000000000003F) // 6 bits mask
footerMagic = uint64(0xBADC0DEBADC0DEC0) // it ends with 6 zero bits which used by index
)

var bits2idx [64]int // bits.Len -> `pools[i]`
// bits2idx maps bits.Len to the index of `pools`
// for size < minMemPoolSize, bits2idx maps to `pools[0]` which is expected.
var bits2idx [64]int

func init() {
i := 0
Expand Down Expand Up @@ -112,7 +117,7 @@ func Malloc(size int) []byte {
// Cap returns the max cap of a buf can be resized to.
// See comment of `Malloc` for details
func Cap(buf []byte) int {
if cap(buf)-len(buf) < footerLen || footer(buf) == 0 {
if cap(buf)-len(buf) < footerLen || getFooter(buf)&footerMagicMask != footerMagic {
panic("buf not malloc by this package or buf len changed without using Cap func")
}
return cap(buf) - footerLen
Expand Down Expand Up @@ -167,7 +172,7 @@ func Free(buf []byte) {
if c-size < footerLen { // size
return
}
footer := footer(buf)
footer := getFooter(buf)
// checks magic
if footer&footerMagicMask != footerMagic {
return
Expand All @@ -181,7 +186,7 @@ func Free(buf []byte) {
}
}

func footer(buf []byte) uint64 {
func getFooter(buf []byte) uint64 {
h := (*sliceHeader)(unsafe.Pointer(&buf))
return *(*uint64)(unsafe.Add(h.Data, h.Cap-footerLen))
}
10 changes: 10 additions & 0 deletions cache/mempool/mempool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ func TestFree(t *testing.T) {
Free(b) // all good
}

func Benchmark_MallocFree(b *testing.B) {
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
b := Malloc(1)
Free(b)
}
})
}

func Benchmark_AppendStr(b *testing.B) {
str := "Benchmark_AppendStr"
b.ReportAllocs()
Expand Down

0 comments on commit 11d91db

Please sign in to comment.