From ddc1a2570aa619135e240ddc05f634b48c2e4d28 Mon Sep 17 00:00:00 2001 From: q191201771 <191201771@qq.com> Date: Wed, 22 Jun 2022 21:42:49 +0800 Subject: [PATCH] =?UTF-8?q?[opt]=20nazabytes::Buffer:=20(1)=20NewBuffer?= =?UTF-8?q?=E7=9A=84initCap=E5=8F=82=E6=95=B0=E6=94=AF=E6=8C=81=E7=94=A80?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=20(2)=20Grow=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E6=89=A9=E5=AE=B9=E5=89=8D=E7=9A=84=E5=A4=A7=E5=B0=8F=E5=A6=82?= =?UTF-8?q?=E6=9E=9C0=E5=88=99=E4=B8=8D=E6=89=93=E5=8D=B0debug=E6=97=A5?= =?UTF-8?q?=E5=BF=97=20(3)=20=E5=A2=9E=E5=8A=A0ResetAndFree=E5=87=BD?= =?UTF-8?q?=E6=95=B0=EF=BC=8C=E9=87=8D=E7=BD=AE=E5=B9=B6=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=8C=81=E6=9C=89=E5=BA=95=E5=B1=82=E5=86=85=E5=AD=98=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/nazabytes/buffer.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/pkg/nazabytes/buffer.go b/pkg/nazabytes/buffer.go index 634f42e..e3a04be 100644 --- a/pkg/nazabytes/buffer.go +++ b/pkg/nazabytes/buffer.go @@ -63,9 +63,11 @@ type Buffer struct { } func NewBuffer(initCap int) *Buffer { - return &Buffer{ - core: make([]byte, initCap, initCap), + b := &Buffer{} + if initCap > 0 { + b.core = make([]byte, initCap, initCap) } + return b } // NewBufferRefBytes @@ -144,7 +146,9 @@ func (b *Buffer) Grow(n int) { // 扩容后总共需要的大小 needed := b.Len() + n - nazalog.Debugf("[%p] Buffer::Grow. realloc, this round need=%d, copy=%d, cap=(%d -> %d)", b, n, b.Len(), b.Cap(), needed) + if len(b.core) != 0 { + nazalog.Debugf("[%p] Buffer::Grow. realloc, this round need=%d, copy=%d, cap=(%d -> %d)", b, n, b.Len(), b.Cap(), needed) + } core := make([]byte, needed, needed) copy(core, b.core[b.rpos:b.wpos]) b.core = core @@ -230,15 +234,21 @@ func (b *Buffer) Truncate(n int) { b.resetIfEmpty() } -// Reset 重置 -// -// 注意,并不会释放内存块 +// Reset 重置。注意,并不会释放内存块,可复用 // func (b *Buffer) Reset() { b.rpos = 0 b.wpos = 0 } +// ResetAndFree 重置并不再持有底层内存块 +// +func (b *Buffer) ResetAndFree() { + b.core = nil + b.rpos = 0 + b.wpos = 0 +} + // --------------------------------------------------------------------------------------------------------------------- // Len Buffer中还没有读的数据的长度