From 6f81292b372a4f63213763bca66a7211a26ec88b Mon Sep 17 00:00:00 2001 From: Carlo Alberto Ferraris Date: Fri, 28 Feb 2020 19:33:23 +0900 Subject: [PATCH] wip --- buffer/pool.go | 18 +++++++++++++++++- buffer/pool_test.go | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/buffer/pool.go b/buffer/pool.go index 07fb4bc..5e97991 100644 --- a/buffer/pool.go +++ b/buffer/pool.go @@ -113,6 +113,14 @@ func (b *Buffer) AppendByte(data byte) { // AppendBytes appends a byte slice to buffer. func (b *Buffer) AppendBytes(data []byte) { + if len(data) <= cap(b.Buf)-len(b.Buf) { + b.Buf = append(b.Buf, data...) // fast path + } else { + b.appendBytesSlow(data) + } +} + +func (b *Buffer) appendBytesSlow(data []byte) { for len(data) > 0 { if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. b.EnsureSpace(1) @@ -128,8 +136,16 @@ func (b *Buffer) AppendBytes(data []byte) { } } -// AppendBytes appends a string to buffer. +// AppendString appends a string to buffer. func (b *Buffer) AppendString(data string) { + if len(data) <= cap(b.Buf)-len(b.Buf) { + b.Buf = append(b.Buf, data...) // fast path + } else { + b.appendStringSlow(data) + } +} + +func (b *Buffer) appendStringSlow(data string) { for len(data) > 0 { if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. b.EnsureSpace(1) diff --git a/buffer/pool_test.go b/buffer/pool_test.go index 680623a..1f321d3 100644 --- a/buffer/pool_test.go +++ b/buffer/pool_test.go @@ -42,7 +42,7 @@ func TestAppendString(t *testing.T) { s := "test" for i := 0; i < 1000; i++ { - b.AppendBytes([]byte(s)) + b.AppendString(s) want = append(want, s...) }