-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Global, official memory pooling for w4. (#132)
- Loading branch information
1 parent
75ed2f9
commit 8f912b3
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package dilithium | ||
|
||
import ( | ||
"sync" | ||
"sync/atomic" | ||
) | ||
|
||
type Buffer struct { | ||
Data []byte | ||
Size uint32 | ||
Used uint32 | ||
refs int32 | ||
pool *Pool | ||
} | ||
|
||
func NewBuffer(pool *Pool) *Buffer { | ||
return &Buffer{ | ||
Data: make([]byte, pool.bufSize), | ||
Size: pool.bufSize, | ||
Used: 0, | ||
refs: 0, | ||
pool: pool, | ||
} | ||
} | ||
|
||
func (buf *Buffer) Ref() { | ||
atomic.AddInt32(&buf.refs, 1) | ||
} | ||
|
||
func (buf *Buffer) Unref() { | ||
if atomic.AddInt32(&buf.refs, -1) < 1 { | ||
buf.Used = 0 | ||
//buf.pool.put(buf) | ||
} | ||
} | ||
|
||
type Pool struct { | ||
id string | ||
bufSize uint32 | ||
store *sync.Pool | ||
} | ||
|
||
func NewPool(id string, bufSize uint32) *Pool { | ||
pool := &Pool{ | ||
id: id, | ||
bufSize: bufSize, | ||
store: new(sync.Pool), | ||
} | ||
pool.store.New = pool.allocate | ||
return pool | ||
} | ||
|
||
func (pool *Pool) Get() *Buffer { | ||
buf := pool.store.Get().(*Buffer) | ||
buf.Ref() | ||
return buf | ||
} | ||
|
||
func (pool *Pool) Put(buf *Buffer) { | ||
pool.store.Put(buf) | ||
} | ||
|
||
func (pool *Pool) allocate() interface{} { | ||
return NewBuffer(pool) | ||
} |