From 5afb307f5522c834363a39fe082557270c861245 Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Thu, 24 Jun 2021 23:01:11 +0300 Subject: [PATCH] Add Buffer.WriteByte and WriteString methods (#691) 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 3f4b86e08..9e929cd98 100644 --- a/buffer/buffer.go +++ b/buffer/buffer.go @@ -106,6 +106,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 96b81c294..b5cd191d2 100644 --- a/buffer/buffer_test.go +++ b/buffer/buffer_test.go @@ -48,6 +48,8 @@ func TestBufferWrites(t *testing.T) { {"AppendFloat32", func() { buf.AppendFloat(float64(float32(3.14)), 32) }, "3.14"}, {"AppendWrite", func() { buf.Write([]byte("foo")) }, "foo"}, {"AppendTime", func() { buf.AppendTime(time.Date(2000, 1, 2, 3, 4, 5, 6, time.UTC), time.RFC3339) }, "2000-01-02T03:04:05Z"}, + {"WriteByte", func() { buf.WriteByte('v') }, "v"}, + {"WriteString", func() { buf.WriteString("foo") }, "foo"}, } for _, tt := range tests {