Don Newton | 98fd881 | 2019-09-23 15:15:02 -0400 | [diff] [blame] | 1 | package goloxi |
| 2 | |
| 3 | import ( |
| 4 | "encoding/binary" |
| 5 | ) |
| 6 | |
| 7 | type Decoder struct { |
| 8 | buffer []byte |
| 9 | offset int |
| 10 | baseOffset int |
| 11 | } |
| 12 | |
| 13 | func NewDecoder(data []byte) *Decoder { |
| 14 | return &Decoder{ |
| 15 | buffer: data, |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | func (d *Decoder) ReadByte() byte { |
| 20 | c := d.buffer[d.offset] |
| 21 | d.offset++ |
| 22 | return c |
| 23 | } |
| 24 | |
| 25 | func (d *Decoder) ReadUint8() uint8 { |
| 26 | i := uint8(d.buffer[d.offset]) |
| 27 | d.offset++ |
| 28 | return i |
| 29 | } |
| 30 | |
| 31 | func (d *Decoder) ReadUint16() uint16 { |
| 32 | i := binary.BigEndian.Uint16(d.buffer[d.offset : d.offset+2]) |
| 33 | d.offset += 2 |
| 34 | return i |
| 35 | } |
| 36 | |
| 37 | func (d *Decoder) ReadUint32() uint32 { |
| 38 | i := binary.BigEndian.Uint32(d.buffer[d.offset : d.offset+4]) |
| 39 | d.offset += 4 |
| 40 | return i |
| 41 | } |
| 42 | |
| 43 | func (d *Decoder) ReadUint64() uint64 { |
| 44 | i := binary.BigEndian.Uint64(d.buffer[d.offset : d.offset+8]) |
| 45 | d.offset += 8 |
| 46 | return i |
| 47 | } |
| 48 | |
| 49 | func (d *Decoder) ReadUint128() Uint128 { |
| 50 | hi := binary.BigEndian.Uint64(d.buffer[d.offset : d.offset+8]) |
| 51 | lo := binary.BigEndian.Uint64(d.buffer[d.offset+8 : d.offset+16]) |
| 52 | d.offset += 16 |
| 53 | return Uint128{ |
| 54 | Hi: hi, |
| 55 | Lo: lo, |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | func (d *Decoder) Skip(n int) { |
| 60 | d.offset += n |
| 61 | } |
| 62 | |
| 63 | func (d *Decoder) SkipAlign() { |
| 64 | d.offset += (d.baseOffset+d.offset+7)/8*8 - d.baseOffset - d.offset |
| 65 | } |
| 66 | |
| 67 | func (d *Decoder) Read(n int) []byte { |
| 68 | data := d.buffer[d.offset : d.offset+n] |
| 69 | d.offset += n |
| 70 | return data |
| 71 | } |
| 72 | |
| 73 | func (d *Decoder) Length() int { |
| 74 | return len(d.buffer) - d.offset |
| 75 | } |
| 76 | |
| 77 | func (d *Decoder) Bytes() []byte { |
| 78 | return d.buffer[d.offset:] |
| 79 | } |
| 80 | |
| 81 | func (d *Decoder) Offset() int { |
| 82 | return d.offset |
| 83 | } |
| 84 | |
| 85 | func (d *Decoder) BaseOffset() int { |
| 86 | return d.baseOffset |
| 87 | } |
| 88 | |
| 89 | func (d *Decoder) SliceDecoder(length, rewind int) *Decoder { |
| 90 | newDecoder := NewDecoder(d.buffer[d.offset : d.offset+length-rewind]) |
| 91 | newDecoder.baseOffset = d.offset + d.baseOffset |
| 92 | d.offset += length - rewind |
| 93 | return newDecoder |
| 94 | } |