github.com/blixtra/rkt@v0.8.1-0.20160204105720-ab0d1add1a43/Godeps/_workspace/src/golang.org/x/net/http2/buffer.go (about) 1 // Copyright 2014 The Go Authors. 2 // See https://code.google.com/p/go/source/browse/CONTRIBUTORS 3 // Licensed under the same terms as Go itself: 4 // https://code.google.com/p/go/source/browse/LICENSE 5 6 package http2 7 8 import ( 9 "errors" 10 ) 11 12 // buffer is an io.ReadWriteCloser backed by a fixed size buffer. 13 // It never allocates, but moves old data as new data is written. 14 type buffer struct { 15 buf []byte 16 r, w int 17 closed bool 18 err error // err to return to reader 19 } 20 21 var ( 22 errReadEmpty = errors.New("read from empty buffer") 23 errWriteClosed = errors.New("write on closed buffer") 24 errWriteFull = errors.New("write on full buffer") 25 ) 26 27 // Read copies bytes from the buffer into p. 28 // It is an error to read when no data is available. 29 func (b *buffer) Read(p []byte) (n int, err error) { 30 n = copy(p, b.buf[b.r:b.w]) 31 b.r += n 32 if b.closed && b.r == b.w { 33 err = b.err 34 } else if b.r == b.w && n == 0 { 35 err = errReadEmpty 36 } 37 return n, err 38 } 39 40 // Len returns the number of bytes of the unread portion of the buffer. 41 func (b *buffer) Len() int { 42 return b.w - b.r 43 } 44 45 // Write copies bytes from p into the buffer. 46 // It is an error to write more data than the buffer can hold. 47 func (b *buffer) Write(p []byte) (n int, err error) { 48 if b.closed { 49 return 0, errWriteClosed 50 } 51 52 // Slide existing data to beginning. 53 if b.r > 0 && len(p) > len(b.buf)-b.w { 54 copy(b.buf, b.buf[b.r:b.w]) 55 b.w -= b.r 56 b.r = 0 57 } 58 59 // Write new data. 60 n = copy(b.buf[b.w:], p) 61 b.w += n 62 if n < len(p) { 63 err = errWriteFull 64 } 65 return n, err 66 } 67 68 // Close marks the buffer as closed. Future calls to Write will 69 // return an error. Future calls to Read, once the buffer is 70 // empty, will return err. 71 func (b *buffer) Close(err error) { 72 if !b.closed { 73 b.closed = true 74 b.err = err 75 } 76 }