| 1 |
package reedsolomon |
| 2 |
|
| 3 |
import "sync" |
| 4 |
|
| 5 |
// WorkAllocator provides external work buffer management for the leopard |
| 6 |
// Reed-Solomon encoder (both GF(2^8) and GF(2^16) variants). When set via |
| 7 |
// [WithWorkAllocator], it replaces the internal sync.Pool used by the leopard |
| 8 |
// encoder for temporary work buffers during Encode and Reconstruct. |
| 9 |
// |
| 10 |
// This only affects the leopard-based encoder ([WithLeopardGF16], [WithLeopardGF]). |
| 11 |
// The classic matrix-based encoder does not use work buffers and ignores this option. |
| 12 |
// |
| 13 |
// This is useful when the caller wants to control buffer lifecycle (e.g., to |
| 14 |
// avoid sync.Pool churn under GC pressure with large buffers). |
| 15 |
// |
| 16 |
// Implementations must be safe for concurrent use: Get and Put may be |
| 17 |
// called from multiple goroutines when the encoder is shared. |
| 18 |
// |
| 19 |
// Get must return n byte slices, each with len and cap >= size. |
| 20 |
// Slices should be SIMD-aligned (64-byte) for optimal performance; see [AllocAligned]. |
| 21 |
// Put is called when the work buffer is no longer needed. |
| 22 |
type WorkAllocator interface { |
| 23 |
Get(n, size int) [][]byte |
| 24 |
Put([][]byte) |
| 25 |
} |
| 26 |
|
| 27 |
// defaultWorkAllocator is the default WorkAllocator backed by sync.Pool. |
| 28 |
type defaultWorkAllocator struct { |
| 29 |
pool sync.Pool |
| 30 |
} |
| 31 |
|
| 32 |
func (a *defaultWorkAllocator) Get(n, size int) [][]byte { |
| 33 |
var work [][]byte |
| 34 |
if w, ok := a.pool.Get().([][]byte); ok { |
| 35 |
work = w |
| 36 |
} |
| 37 |
if cap(work) >= n { |
| 38 |
work = work[:n] |
| 39 |
} else { |
| 40 |
work = AllocAligned(n, size) |
| 41 |
} |
| 42 |
for i := range work { |
| 43 |
if cap(work[i]) < size { |
| 44 |
work[i] = AllocAligned(1, size)[0] |
| 45 |
} else { |
| 46 |
work[i] = work[i][:size] |
| 47 |
} |
| 48 |
} |
| 49 |
return work |
| 50 |
} |
| 51 |
|
| 52 |
func (a *defaultWorkAllocator) Put(work [][]byte) { |
| 53 |
a.pool.Put(work) |
| 54 |
} |