aboutsummaryrefslogtreecommitdiffstats
path: root/utils/sync/bytes.go
diff options
context:
space:
mode:
authorMáximo Cuadros <mcuadros@gmail.com>2022-11-07 16:55:53 +0100
committerGitHub <noreply@github.com>2022-11-07 16:55:53 +0100
commitf37bb587b6634435afb5069b2101cb4e0ff78d63 (patch)
tree9e6ace8591fff4e95f982304842f0bf8512bd612 /utils/sync/bytes.go
parent652bc83fe45c114440de41d7e0fecf3e4b9e517d (diff)
parenta2c309de872dc18053acb186b1ec125d1f723a90 (diff)
downloadgo-git-f37bb587b6634435afb5069b2101cb4e0ff78d63.tar.gz
Merge pull request #608 from pjbgf/optimise-zlib-reader
Optimise zlib reader and consolidate sync.Pools
Diffstat (limited to 'utils/sync/bytes.go')
-rw-r--r--utils/sync/bytes.go51
1 files changed, 51 insertions, 0 deletions
diff --git a/utils/sync/bytes.go b/utils/sync/bytes.go
new file mode 100644
index 0000000..dd06fc0
--- /dev/null
+++ b/utils/sync/bytes.go
@@ -0,0 +1,51 @@
+package sync
+
+import (
+ "bytes"
+ "sync"
+)
+
+var (
+ byteSlice = sync.Pool{
+ New: func() interface{} {
+ b := make([]byte, 16*1024)
+ return &b
+ },
+ }
+ bytesBuffer = sync.Pool{
+ New: func() interface{} {
+ return bytes.NewBuffer(nil)
+ },
+ }
+)
+
+// GetByteSlice returns a *[]byte that is managed by a sync.Pool.
+// The initial slice length will be 16384 (16kb).
+//
+// After use, the *[]byte should be put back into the sync.Pool
+// by calling PutByteSlice.
+func GetByteSlice() *[]byte {
+ buf := byteSlice.Get().(*[]byte)
+ return buf
+}
+
+// PutByteSlice puts buf back into its sync.Pool.
+func PutByteSlice(buf *[]byte) {
+ byteSlice.Put(buf)
+}
+
+// GetBytesBuffer returns a *bytes.Buffer that is managed by a sync.Pool.
+// Returns a buffer that is resetted and ready for use.
+//
+// After use, the *bytes.Buffer should be put back into the sync.Pool
+// by calling PutBytesBuffer.
+func GetBytesBuffer() *bytes.Buffer {
+ buf := bytesBuffer.Get().(*bytes.Buffer)
+ buf.Reset()
+ return buf
+}
+
+// PutBytesBuffer puts buf back into its sync.Pool.
+func PutBytesBuffer(buf *bytes.Buffer) {
+ bytesBuffer.Put(buf)
+}