github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/net/http2/fixed_buffer.go (about) 1 // Copyright 2014 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package http2 6 7 import ( 8 "errors" 9 ) 10 11 // fixedBuffer is an io.ReadWriter backed by a fixed size buffer. 12 // It never allocates, but moves old data as new data is written. 13 type fixedBuffer struct { 14 buf []byte 15 r, w int 16 } 17 18 var ( 19 errReadEmpty = errors.New("read from empty fixedBuffer") 20 errWriteFull = errors.New("write on full fixedBuffer") 21 ) 22 23 // Read copies bytes from the buffer into p. 24 // It is an error to read when no data is available. 25 func (b *fixedBuffer) Read(p []byte) (n int, err error) { 26 if b.r == b.w { 27 return 0, errReadEmpty 28 } 29 n = copy(p, b.buf[b.r:b.w]) 30 b.r += n 31 if b.r == b.w { 32 b.r = 0 33 b.w = 0 34 } 35 return n, nil 36 } 37 38 // Len returns the number of bytes of the unread portion of the buffer. 39 func (b *fixedBuffer) Len() int { 40 return b.w - b.r 41 } 42 43 // Write copies bytes from p into the buffer. 44 // It is an error to write more data than the buffer can hold. 45 func (b *fixedBuffer) Write(p []byte) (n int, err error) { 46 // Slide existing data to beginning. 47 if b.r > 0 && len(p) > len(b.buf)-b.w { 48 copy(b.buf, b.buf[b.r:b.w]) 49 b.w -= b.r 50 b.r = 0 51 } 52 53 // Write new data. 54 n = copy(b.buf[b.w:], p) 55 b.w += n 56 if n < len(p) { 57 err = errWriteFull 58 } 59 return n, err 60 }