encode.go
1 package codec 2 3 import ( 4 "encoding/binary" 5 ) 6 7 type Encoder struct { 8 buf []byte 9 } 10 11 func Encode(size_hint int) *Encoder { 12 return &Encoder{buf: make([]byte, 0, size_hint)} 13 } 14 15 // Get the encoded array of bytes 16 func (e *Encoder) Result() []byte { 17 return e.buf 18 } 19 20 func (e *Encoder) Bytes(b []byte) { 21 e.buf = append(e.buf, b...) 22 } 23 24 func (e *Encoder) Bool(b bool) { 25 var v byte = 0 26 if b { 27 v = 1 28 } 29 e.buf = append(e.buf, v) 30 } 31 32 func (e *Encoder) UInt8(v uint8) { 33 e.buf = append(e.buf, v) 34 } 35 36 func (e *Encoder) UInt16le(v uint16) { 37 e.buf = binary.LittleEndian.AppendUint16(e.buf, v) 38 } 39 40 func (e *Encoder) UInt16be(v uint16) { 41 e.buf = binary.BigEndian.AppendUint16(e.buf, v) 42 } 43 44 func (e *Encoder) UInt32le(v uint32) { 45 e.buf = binary.LittleEndian.AppendUint32(e.buf, v) 46 } 47 48 func (e *Encoder) UInt32be(v uint32) { 49 e.buf = binary.BigEndian.AppendUint32(e.buf, v) 50 } 51 52 func (e *Encoder) UInt64le(v uint64) { 53 e.buf = binary.LittleEndian.AppendUint64(e.buf, v) 54 } 55 56 func (e *Encoder) Int64le(v int64) { 57 e.buf = binary.LittleEndian.AppendUint64(e.buf, uint64(v)) 58 } 59 60 func (e *Encoder) VarUInt(val uint64) { 61 if val < 0xFD { 62 e.buf = append(e.buf, byte(val)) 63 } else if val <= 0xFFFF { 64 e.buf = append(e.buf, 0xFD) 65 e.buf = binary.LittleEndian.AppendUint16(e.buf, uint16(val)) 66 } else if val <= 0xFFFFFFFF { 67 e.buf = append(e.buf, 0xFE) 68 e.buf = binary.LittleEndian.AppendUint32(e.buf, uint32(val)) 69 } else { 70 e.buf = append(e.buf, 0xFF) 71 e.buf = binary.LittleEndian.AppendUint64(e.buf, val) 72 } 73 } 74 75 func (e *Encoder) VarString(v string) { 76 b := []byte(v) 77 e.VarUInt(uint64(len(b))) 78 e.buf = append(e.buf, b...) 79 } 80 81 func (e *Encoder) PadString(size uint64, v string) { 82 bytes := []byte(v) 83 e.buf = append(e.buf, bytes[0:size]...) 84 used := uint64(len(v)) 85 for used < size { 86 e.buf = append(e.buf, 0) 87 } 88 }