Skip to content

Commit

Permalink
Add Buffer.WriteByte and WriteString methods (#691)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
smira authored Jun 24, 2021
1 parent fb71758 commit 5afb307
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
18 changes: 18 additions & 0 deletions buffer/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions buffer/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 5afb307

Please sign in to comment.