Mining/pkg/mining/bufpool.go
Claude 0545d43685
Some checks are pending
Security Scan / security (push) Waiting to run
Test / test (push) Waiting to run
ax(mining): replace prose comments with usage examples in bufpool.go
AX Principle 2: comments must show HOW with real values, not restate
the type signature. Four prose-style doc comments converted to
concrete call-site examples.

Co-Authored-By: Charon <charon@lethean.io>
2026-04-02 10:30:29 +01:00

60 lines
1.5 KiB
Go

package mining
import (
"bytes"
"encoding/json"
"sync"
)
// bufferPool provides reusable byte buffers for JSON encoding.
// This reduces allocation overhead in hot paths like WebSocket event serialization.
var bufferPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 1024))
},
}
// buf := getBuffer()
// defer putBuffer(buf)
func getBuffer() *bytes.Buffer {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
// defer putBuffer(buf) // return buf after use; buffers >64KB are discarded
func putBuffer(buf *bytes.Buffer) {
// Don't pool buffers that grew too large (>64KB)
if buf.Cap() <= 65536 {
bufferPool.Put(buf)
}
}
// UnmarshalJSON(data, &msg)
func UnmarshalJSON(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}
// data, err := MarshalJSON(stats) // pooled buffer; safe to hold after call
func MarshalJSON(v interface{}) ([]byte, error) {
buf := getBuffer()
defer putBuffer(buf)
encoder := json.NewEncoder(buf)
// Don't escape HTML characters (matches json.Marshal behavior for these use cases)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(v); err != nil {
return nil, err
}
// json.Encoder.Encode adds a newline; remove it to match json.Marshal
data := buf.Bytes()
if len(data) > 0 && data[len(data)-1] == '\n' {
data = data[:len(data)-1]
}
// Return a copy since the buffer will be reused
result := make([]byte, len(data))
copy(result, data)
return result, nil
}