github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/util/capped_writer.go (about) 1 package util 2 3 import ( 4 "bytes" 5 6 "github.com/pkg/errors" 7 ) 8 9 // CappedWriter implements a buffer that stores up to MaxBytes bytes. 10 // Returns ErrBufferFull on overflowing writes 11 type CappedWriter struct { 12 Buffer *bytes.Buffer 13 MaxBytes int 14 } 15 16 // ErrBufferFull indicates that a CappedWriter's bytes.Buffer has MaxBytes bytes. 17 var ErrBufferFull = errors.New("buffer full") 18 19 // Write writes to the buffer. An error is returned if the buffer is full. 20 func (cw *CappedWriter) Write(in []byte) (int, error) { 21 remaining := cw.MaxBytes - cw.Buffer.Len() 22 if len(in) <= remaining { 23 return cw.Buffer.Write(in) 24 } 25 // fill up the remaining buffer and return an error 26 n, _ := cw.Buffer.Write(in[:remaining]) 27 return n, ErrBufferFull 28 } 29 30 // IsFull indicates whether the buffer is full. 31 func (cw *CappedWriter) IsFull() bool { 32 return cw.Buffer.Len() == cw.MaxBytes 33 } 34 35 // String return the contents of the buffer as a string. 36 func (cw *CappedWriter) String() string { 37 return cw.Buffer.String() 38 }