zen/core/zlog/buffer.go

76 lines
1.3 KiB
Go
Raw Normal View History

2024-08-23 10:18:27 +07:00
package zlog
import (
"bytes"
"log/slog"
"sync"
)
type jsonHandlerPool struct {
*sync.Pool
}
func newJsonHandlerPool(handlerOption *slog.HandlerOptions) *jsonHandlerPool {
var handlerPool *jsonHandlerPool
generator := &sync.Pool{
New: func() any {
buf := new(bytes.Buffer)
return &jsonHandler{
2024-08-23 12:29:47 +07:00
buf: buf,
2024-08-23 10:18:27 +07:00
pool: handlerPool,
JSONHandler: slog.NewJSONHandler(buf, handlerOption),
}
},
}
handlerPool = &jsonHandlerPool{
generator,
}
return handlerPool
}
func (jhp *jsonHandlerPool) Get() *jsonHandler {
handler := jhp.Pool.Get().(*jsonHandler)
return handler
}
type jsonHandler struct {
2024-08-23 12:29:47 +07:00
buf *bytes.Buffer
2024-08-23 10:18:27 +07:00
pool *jsonHandlerPool
*slog.JSONHandler
}
func (j *jsonHandler) Put() {
// Only put back to pool if buffer is smaller than 4MB in RAM size.
2024-08-23 12:29:47 +07:00
if j.buf.Cap() < 1024*1024*4 {
j.buf.Reset()
2024-08-23 10:18:27 +07:00
j.pool.Put(j)
}
}
type bufferPool struct {
*sync.Pool
}
func newBufferPool() *bufferPool {
return &bufferPool{
&sync.Pool{
New: func() any {
buf := new(bytes.Buffer)
buf.Grow(1024)
return buf
},
},
}
}
func (bp *bufferPool) Get() *bytes.Buffer {
return bp.Pool.Get().(*bytes.Buffer)
}
func (bp *bufferPool) Put(buf *bytes.Buffer) {
if buf.Cap() < 1024*1024*4 {
buf.Reset()
bp.Pool.Put(buf)
}
}