Skip to content

Commit

Permalink
add SyncBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
sysulq authored and moisesvega committed May 25, 2021
1 parent b1a95ff commit 6d58a7d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
26 changes: 26 additions & 0 deletions internal/ztest/writer.go
Expand Up @@ -25,6 +25,7 @@ import (
"errors"
"io/ioutil"
"strings"
"sync"
)

// A Syncer is a spy for the Sync portion of zapcore.WriteSyncer.
Expand Down Expand Up @@ -94,3 +95,28 @@ func (b *Buffer) Lines() []string {
func (b *Buffer) Stripped() string {
return strings.TrimRight(b.String(), "\n")
}

// SyncBuffer is an implementation of bytes.Buffer which is goroutine safe.
type SyncBuffer struct {
sync.RWMutex

buf bytes.Buffer
}

// Write appends the contents of p to the buffer, growing the buffer as
// needed.
func (b *SyncBuffer) Write(p []byte) (n int, err error) {
b.Lock()
defer b.Unlock()

return b.buf.Write(p)
}

// String returns the contents of the unread portion of the buffer
// as a string.
func (b *SyncBuffer) String() string {
b.RLock()
defer b.RUnlock()

return b.buf.String()
}
2 changes: 1 addition & 1 deletion zapcore/write_syncer_test.go
Expand Up @@ -122,7 +122,7 @@ func TestBufferWriter(t *testing.T) {
})

t.Run("flush timer", func(t *testing.T) {
buf := &bytes.Buffer{}
buf := &ztest.SyncBuffer{}
ws, close := Buffer(AddSync(buf), 6, time.Microsecond)
defer close()
requireWriteWorks(t, ws)
Expand Down

0 comments on commit 6d58a7d

Please sign in to comment.