diff --git a/synchelper/bytes_buffer_pool.go b/synchelper/bytes_buffer_pool.go new file mode 100644 index 0000000..56f4405 --- /dev/null +++ b/synchelper/bytes_buffer_pool.go @@ -0,0 +1,18 @@ +package synchelper + +import "bytes" + +// NewBytesBufferPool 返回新的 BytesBufferPool +func NewBytesBufferPool(initialSize, maximumSize int) BytesBufferPool { + return NewPool( + func() any { + return bytes.NewBuffer(make([]byte, 0, initialSize)) + }, + func(v *bytes.Buffer) bool { + return v.Cap() <= maximumSize + }, + ) +} + +// BytesBufferPool 是 [*bytes.Buffer] 的资源池 +type BytesBufferPool = Pool[*bytes.Buffer] diff --git a/synchelper/go.mod b/synchelper/go.mod new file mode 100644 index 0000000..03f664a --- /dev/null +++ b/synchelper/go.mod @@ -0,0 +1,3 @@ +module git.blauwelle.com/go/crate/synchelper + +go 1.20 diff --git a/synchelper/io_writer.go b/synchelper/io_writer.go new file mode 100644 index 0000000..d3ae9f6 --- /dev/null +++ b/synchelper/io_writer.go @@ -0,0 +1,25 @@ +package synchelper + +import ( + "io" + "sync" +) + +// NewSyncWriter 返回写互斥的 writer +func NewSyncWriter(writer io.Writer) io.Writer { + return &syncWriter{ + writer: writer, + lock: sync.Mutex{}, + } +} + +type syncWriter struct { + writer io.Writer + lock sync.Mutex +} + +func (w *syncWriter) Write(p []byte) (n int, err error) { + w.lock.Lock() + defer w.lock.Unlock() + return w.writer.Write(p) +} diff --git a/synchelper/pool.go b/synchelper/pool.go new file mode 100644 index 0000000..fba75b8 --- /dev/null +++ b/synchelper/pool.go @@ -0,0 +1,34 @@ +package synchelper + +import ( + "sync" +) + +// NewPool 初始化 Pool, +// newFn 是资源的构造函数, +// putCond 返回 true 时表示资源可以被放回 Pool 中. +func NewPool[T any](newFn func() any, putCond func(v T) bool) Pool[T] { + return Pool[T]{ + pool: &sync.Pool{New: newFn}, + putCond: putCond, + } +} + +// Pool 是通用的资源池 +type Pool[T any] struct { + pool *sync.Pool + putCond func(v T) bool +} + +// Get 获取资源 +func (pool Pool[T]) Get() T { + return pool.pool.Get().(T) +} + +// Put 放回资源 +func (pool Pool[T]) Put(v T) { + if !pool.putCond(v) { + return + } + pool.pool.Put(v) +}