github.com/shaoyuan1943/gokcp@v0.0.0-20201026071748-5b36d4c87f61/codec.go (about) 1 package gokcp 2 3 import "encoding/binary" 4 5 func encode8u(p []byte, c byte) []byte { 6 p[0] = c 7 return p[1:] 8 } 9 10 func decode8u(p []byte, c *byte) []byte { 11 *c = p[0] 12 return p[1:] 13 } 14 15 func encode16u(p []byte, w uint16) []byte { 16 binary.LittleEndian.PutUint16(p, w) 17 return p[2:] 18 } 19 20 func decode16u(p []byte, w *uint16) []byte { 21 *w = binary.LittleEndian.Uint16(p) 22 return p[2:] 23 } 24 25 func encode32u(p []byte, l uint32) []byte { 26 binary.LittleEndian.PutUint32(p, l) 27 return p[4:] 28 } 29 30 func decode32u(p []byte, l *uint32) []byte { 31 *l = binary.LittleEndian.Uint32(p) 32 return p[4:] 33 } 34 35 func encode64u(p []byte, l uint64) []byte { 36 binary.LittleEndian.PutUint64(p, l) 37 return p[8:] 38 } 39 40 func decode64u(p []byte, l *uint64) []byte { 41 *l = binary.LittleEndian.Uint64(p) 42 return p[8:] 43 } 44 45 func min(a, b uint32) uint32 { 46 if a <= b { 47 return a 48 } 49 return b 50 } 51 52 func max(a, b uint32) uint32 { 53 if a >= b { 54 return a 55 } 56 return b 57 } 58 59 func bound(lower, middle, upper uint32) uint32 { 60 return min(max(lower, middle), upper) 61 } 62 63 func timediff(later, earlier uint32) int32 { 64 return (int32)(later - earlier) 65 } 66 67 func encodeSegment(data []byte, seg *segment) []byte { 68 rawseg := encode32u(data, seg.convID) // 4 69 rawseg = encode8u(rawseg, uint8(seg.cmd)) // 1 70 rawseg = encode8u(rawseg, uint8(seg.frg)) // 1 71 rawseg = encode16u(rawseg, uint16(seg.wnd)) // 2 72 rawseg = encode32u(rawseg, seg.ts) // 4 73 rawseg = encode32u(rawseg, seg.sn) // 4 74 rawseg = encode32u(rawseg, seg.una) // 4 75 rawseg = encode32u(rawseg, uint32(len(seg.dataBuffer))) // 4 76 return rawseg // total 24 77 }