From 52fd0e53caf3bba4f2dd5c69880f8bb6caecd03a Mon Sep 17 00:00:00 2001 From: Carlo Alberto Ferraris Date: Fri, 28 Feb 2020 19:04:54 +0900 Subject: [PATCH] Make Buffer.EnsureSpace inlineable Split the slow path into a separate function, so that the fast path in EnsureSpace becomes inlineable. This allows code in jwriter to inline the fast path. --- buffer/pool.go | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/buffer/pool.go b/buffer/pool.go index 07fb4bc..4c508f7 100644 --- a/buffer/pool.go +++ b/buffer/pool.go @@ -78,9 +78,12 @@ type Buffer struct { // EnsureSpace makes sure that the current chunk contains at least s free bytes, // possibly creating a new chunk. func (b *Buffer) EnsureSpace(s int) { - if cap(b.Buf)-len(b.Buf) >= s { - return + if cap(b.Buf)-len(b.Buf) < s { + b.ensureSpaceSlow(s) } +} + +func (b *Buffer) ensureSpaceSlow(s int) { l := len(b.Buf) if l > 0 { if cap(b.toPool) != cap(b.Buf) { @@ -105,18 +108,14 @@ func (b *Buffer) EnsureSpace(s int) { // AppendByte appends a single byte to buffer. func (b *Buffer) AppendByte(data byte) { - if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. - b.EnsureSpace(1) - } + b.EnsureSpace(1) b.Buf = append(b.Buf, data) } // AppendBytes appends a byte slice to buffer. func (b *Buffer) AppendBytes(data []byte) { for len(data) > 0 { - if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. - b.EnsureSpace(1) - } + b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) if sz > len(data) { @@ -131,9 +130,7 @@ func (b *Buffer) AppendBytes(data []byte) { // AppendBytes appends a string to buffer. func (b *Buffer) AppendString(data string) { for len(data) > 0 { - if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. - b.EnsureSpace(1) - } + b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) if sz > len(data) {