Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: bytes pool #7

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions pool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package genh

import "sync"

type BytesPool struct {
m LMap[uint32, *sync.Pool]
}

func (mp *BytesPool) Get(sz uint32) []byte {
if sz = sz - (sz % 1024); sz < 1024 { // round to the nearest kb
sz = 1024
}
return *(mp.pool(sz).Get().(*[]byte))
}

func (mp *BytesPool) Put(b []byte) uint32 {
if cap(b) < 1024 {
return 0
}
sz := uint32(cap(b))
if sz = sz - (sz % 1024); sz < 1024 { // round to the nearest kb
sz = 1024
}
b = b[:0:sz]
mp.pool(sz).Put(&b)
return sz
}

func (mp *BytesPool) pool(sz uint32) *sync.Pool {
return mp.m.MustGet(sz, func() *sync.Pool {
p := sync.Pool{
New: func() any {
b := make([]byte, 0, sz)
return &b
},
}
return &p
})

}
40 changes: 0 additions & 40 deletions sync.go

This file was deleted.

15 changes: 15 additions & 0 deletions timed.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ func (tm *TimedMap[K, V]) Set(k K, v V, timeout time.Duration) {
tm.m.Set(k, ele)
}

func (tm *TimedMap[K, V]) MustGet(k K, vfn func() V, timeout time.Duration) (out V) {
var ok bool
if out, ok = tm.GetOk(k); ok {
return
}
out = vfn()
ele := &tmEle[V]{v: out, ttl: timeout}
ele.la.Store(time.Now().UnixNano())
if timeout > 0 {
ele.t = time.AfterFunc(timeout, func() { tm.deleteEle(k, ele) })
}
tm.m.Set(k, ele)
return
}

func (tm *TimedMap[K, V]) SetUpdateFn(k K, vfn func() V, updateEvery time.Duration) {
tm.SetUpdateExpireFn(k, vfn, updateEvery, -1)
}
Expand Down
Loading