Skip to content
Snippets Groups Projects
concurrent_buffer.go 963 B
Newer Older
  • Learn to ignore specific revisions
  • package core
    
    import (
    	"bytes"
    	"sync"
    )
    
    // Implement something very much like bytes.Buffer, but with
    // thread-safe methods.
    type concurrentbuffer struct {
    	buf bytes.Buffer
    
    // Implement io.Reader.
    
    func (b *concurrentbuffer) Read(p []byte) (n int, err error) {
    	b.mu.Lock()
    
    	defer b.mu.Unlock()
    
    // Implement io.Writer.
    
    func (b *concurrentbuffer) Write(p []byte) (n int, err error) {
    	b.mu.Lock()
    
    	defer b.mu.Unlock()
    
    // Truncate the buffer to 0 elements.
    func (b *concurrentbuffer) Reset() {
    
    	defer b.mu.Unlock()
    
    	b.buf.Reset()
    }
    
    // Return a deep copy of the underlying bytes.
    func (b *concurrentbuffer) Bytes() []byte {
    	b.mu.RLock()
    	defer b.mu.RUnlock()
    
    	src := b.buf.Bytes()
    	return append([]byte(nil), src...)
    }
    
    // Return a printable version of the buffer.
    func (b *concurrentbuffer) String() string {
    	b.mu.RLock()
    	defer b.mu.RUnlock()
    
    
    	return b.buf.String()
    }