go-p2p/node/buffer_pool.go
Virgil dec79b54d6
All checks were successful
Security Scan / security (push) Successful in 10s
Test / test (push) Successful in 1m40s
refactor(node): clarify filesystem and buffer pool names
Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-30 21:50:35 +00:00

53 lines
1.4 KiB
Go

package node
import (
"bytes"
"sync"
core "dappco.re/go/core"
)
// bufferPool provides reusable byte buffers for JSON encoding in hot paths.
// This reduces allocation overhead in message serialization.
var bufferPool = sync.Pool{
New: func() any {
return bytes.NewBuffer(make([]byte, 0, 1024))
},
}
// getBuffer retrieves a buffer from the pool.
func getBuffer() *bytes.Buffer {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
// putBuffer returns a buffer to the pool.
func putBuffer(buf *bytes.Buffer) {
// Don't pool buffers that grew too large (>64KB)
if buf.Cap() <= 65536 {
bufferPool.Put(buf)
}
}
// MarshalJSON encodes a value to JSON using Core's JSON primitive and then
// restores the historical no-EscapeHTML behaviour expected by the node package.
// Returns a copy of the encoded bytes (safe to use after the function returns).
//
// data, err := MarshalJSON(v)
func MarshalJSON(v any) ([]byte, error) {
encoded := core.JSONMarshal(v)
if !encoded.OK {
return nil, encoded.Value.(error)
}
data := encoded.Value.([]byte)
data = bytes.ReplaceAll(data, []byte(`\u003c`), []byte("<"))
data = bytes.ReplaceAll(data, []byte(`\u003e`), []byte(">"))
data = bytes.ReplaceAll(data, []byte(`\u0026`), []byte("&"))
// Return a copy since callers may retain the slice after subsequent calls.
out := make([]byte, len(data))
copy(out, data)
return out, nil
}