blob: aa974b9701cbb3b7c3921824edd8597cc7088134 [file] [log] [blame]
Don Newton98fd8812019-09-23 15:15:02 -04001package goloxi
2
3import (
4 "encoding/binary"
5)
6
7type Decoder struct {
8 buffer []byte
9 offset int
10 baseOffset int
11}
12
13func NewDecoder(data []byte) *Decoder {
14 return &Decoder{
15 buffer: data,
16 }
17}
18
19func (d *Decoder) ReadByte() byte {
20 c := d.buffer[d.offset]
21 d.offset++
22 return c
23}
24
25func (d *Decoder) ReadUint8() uint8 {
26 i := uint8(d.buffer[d.offset])
27 d.offset++
28 return i
29}
30
31func (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
37func (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
43func (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
49func (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
59func (d *Decoder) Skip(n int) {
60 d.offset += n
61}
62
63func (d *Decoder) SkipAlign() {
64 d.offset += (d.baseOffset+d.offset+7)/8*8 - d.baseOffset - d.offset
65}
66
67func (d *Decoder) Read(n int) []byte {
68 data := d.buffer[d.offset : d.offset+n]
69 d.offset += n
70 return data
71}
72
73func (d *Decoder) Length() int {
74 return len(d.buffer) - d.offset
75}
76
77func (d *Decoder) Bytes() []byte {
78 return d.buffer[d.offset:]
79}
80
81func (d *Decoder) Offset() int {
82 return d.offset
83}
84
85func (d *Decoder) BaseOffset() int {
86 return d.baseOffset
87}
88
89func (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}