github.com/FlowerWrong/netstack@v0.0.0-20191009141956-e5848263af28/tcpip/buffer/prependable.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package buffer 16 17 // Prependable is a buffer that grows backwards, that is, more data can be 18 // prepended to it. It is useful when building networking packets, where each 19 // protocol adds its own headers to the front of the higher-level protocol 20 // header and payload; for example, TCP would prepend its header to the payload, 21 // then IP would prepend its own, then ethernet. 22 type Prependable struct { 23 // Buf is the buffer backing the prependable buffer. 24 buf View 25 26 // usedIdx is the index where the used part of the buffer begins. 27 usedIdx int 28 } 29 30 // NewPrependable allocates a new prependable buffer with the given size. 31 func NewPrependable(size int) Prependable { 32 return Prependable{buf: NewView(size), usedIdx: size} 33 } 34 35 // NewPrependableFromView creates an entirely-used Prependable from a View. 36 // 37 // NewPrependableFromView takes ownership of v. Note that since the entire 38 // prependable is used, further attempts to call Prepend will note that size > 39 // p.usedIdx and return nil. 40 func NewPrependableFromView(v View) Prependable { 41 return Prependable{buf: v, usedIdx: 0} 42 } 43 44 // View returns a View of the backing buffer that contains all prepended 45 // data so far. 46 func (p Prependable) View() View { 47 return p.buf[p.usedIdx:] 48 } 49 50 // UsedLength returns the number of bytes used so far. 51 func (p Prependable) UsedLength() int { 52 return len(p.buf) - p.usedIdx 53 } 54 55 // AvailableLength returns the number of bytes used so far. 56 func (p Prependable) AvailableLength() int { 57 return p.usedIdx 58 } 59 60 // TrimBack removes size bytes from the end. 61 func (p *Prependable) TrimBack(size int) { 62 p.buf = p.buf[:len(p.buf)-size] 63 } 64 65 // Prepend reserves the requested space in front of the buffer, returning a 66 // slice that represents the reserved space. 67 func (p *Prependable) Prepend(size int) []byte { 68 if size > p.usedIdx { 69 return nil 70 } 71 72 p.usedIdx -= size 73 return p.View()[:size:size] 74 }