github.com/shaoyuan1943/gokcp@v0.0.0-20201026071748-5b36d4c87f61/kcp_buffer.go (about)

     1  package gokcp
     2  
     3  import (
     4  	"encoding/binary"
     5  )
     6  
     7  type Buffer struct {
     8  	srcBuffer []byte
     9  	buffer    []byte
    10  	segBuffer []byte
    11  	reserved  int
    12  }
    13  
    14  func NewBuffer(size int, reserved int) *Buffer {
    15  	b := &Buffer{
    16  		buffer:    make([]byte, size),
    17  		segBuffer: make([]byte, KCP_OVERHEAD),
    18  	}
    19  
    20  	b.reserved = reserved
    21  	b.srcBuffer = b.buffer
    22  	b.buffer = b.buffer[reserved:]
    23  	b.buffer = b.buffer[:0]
    24  	return b
    25  }
    26  
    27  func (b *Buffer) Reset() {
    28  	b.buffer = b.buffer[:0]
    29  }
    30  
    31  func (b *Buffer) Write(p []byte) {
    32  	b.buffer = append(b.buffer, p...)
    33  }
    34  
    35  func (b *Buffer) WriteOverHeader(seg *segment) {
    36  	binary.LittleEndian.PutUint32(b.segBuffer, seg.convID)
    37  	b.segBuffer[4] = byte(seg.cmd)
    38  	b.segBuffer[5] = byte(seg.frg)
    39  	binary.LittleEndian.PutUint16(b.segBuffer[6:], uint16(seg.wnd))
    40  	binary.LittleEndian.PutUint32(b.segBuffer[8:], seg.ts)
    41  	binary.LittleEndian.PutUint32(b.segBuffer[12:], seg.sn)
    42  	binary.LittleEndian.PutUint32(b.segBuffer[16:], seg.una)
    43  	binary.LittleEndian.PutUint32(b.segBuffer[20:], uint32(len(seg.dataBuffer)))
    44  	b.segBuffer = b.segBuffer[0:]
    45  	b.Write(b.segBuffer)
    46  }
    47  
    48  func (b *Buffer) CompareDiff(size int) bool {
    49  	return len(b.buffer) > size
    50  }
    51  
    52  func (b *Buffer) Data() []byte {
    53  	return b.buffer
    54  }
    55  
    56  func (b *Buffer) RawData() []byte {
    57  	return b.srcBuffer[:len(b.buffer)+b.reserved]
    58  }
    59  
    60  func (b *Buffer) Len() int {
    61  	return len(b.buffer)
    62  }
    63  
    64  func (b *Buffer) RawLen() int {
    65  	return len(b.buffer) + b.reserved
    66  }