Skip to content

Instantly share code, notes, and snippets.

@Fallenstedt
Forked from arkan/safebuffer.go
Created May 19, 2021 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fallenstedt/56ec7156db0d33e38d719c1e0558cdd3 to your computer and use it in GitHub Desktop.
Save Fallenstedt/56ec7156db0d33e38d719c1e0558cdd3 to your computer and use it in GitHub Desktop.
Golang: Buffer is a goroutine safe bytes.Buffer
package safebuffer
import (
"bytes"
"sync"
)
// Buffer is a goroutine safe bytes.Buffer
type Buffer struct {
buffer bytes.Buffer
mutex sync.Mutex
}
// Write appends the contents of p to the buffer, growing the buffer as needed. It returns
// the number of bytes written.
func (s *Buffer) Write(p []byte) (n int, err error) {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.buffer.Write(p)
}
// String returns the contents of the unread portion of the buffer
// as a string. If the Buffer is a nil pointer, it returns "<nil>".
func (s *Buffer) String() string {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.buffer.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment