From 5640fd8396533d3715840e4cbadcf4828c84067a Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Tue, 26 Mar 2019 01:01:50 +0300 Subject: [PATCH] Add Buffer.WriteByte and WriteString methods These methods are equivalent to `AppendByte` and `AppendString`, but their signatures are compatible with [bytes.Buffer](https://godoc.org/bytes#Buffer) and [bufio.Writer](https://godoc.org/bufio#Writer). This allows to use `Buffer` where `bytes.Buffer` was expected without extra cost of wrapping. One example is msgpack library which expects `Writer` to implement `WriteByte` and `WriteString`, otherwise it is wrapped which incurs extra allocation: https://github.com/vmihailenco/msgpack/blob/master/encode.go#L63-L67 --- buffer/buffer.go | 18 ++++++++++++++++++ buffer/buffer_test.go | 2 ++ 2 files changed, 20 insertions(+) diff --git a/buffer/buffer.go b/buffer/buffer.go index 7592e8c63..c2e3df8d2 100644 --- a/buffer/buffer.go +++ b/buffer/buffer.go @@ -98,6 +98,24 @@ func (b *Buffer) Write(bs []byte) (int, error) { return len(bs), nil } +// WriteByte writes a single byte to the Buffer. +// +// Error returned is always nil, function signature is compatible +// with bytes.Buffer and bufio.Writer +func (b *Buffer) WriteByte(v byte) error { + b.AppendByte(v) + return nil +} + +// WriteString writes a string to the Buffer. +// +// Error returned is always nil, function signature is compatible +// with bytes.Buffer and bufio.Writer +func (b *Buffer) WriteString(s string) (int, error) { + b.AppendString(s) + return len(s), nil +} + // TrimNewline trims any final "\n" byte from the end of the buffer. func (b *Buffer) TrimNewline() { if i := len(b.bs) - 1; i >= 0 { diff --git a/buffer/buffer_test.go b/buffer/buffer_test.go index 59bc08a6a..8cf1a37c6 100644 --- a/buffer/buffer_test.go +++ b/buffer/buffer_test.go @@ -46,6 +46,8 @@ func TestBufferWrites(t *testing.T) { // Intenationally introduce some floating-point error. {"AppendFloat32", func() { buf.AppendFloat(float64(float32(3.14)), 32) }, "3.14"}, {"AppendWrite", func() { buf.Write([]byte("foo")) }, "foo"}, + {"WriteByte", func() { buf.WriteByte('v') }, "v"}, + {"WriteString", func() { buf.WriteString("foo") }, "foo"}, } for _, tt := range tests {