-
Notifications
You must be signed in to change notification settings - Fork 23
/
reader.go
146 lines (122 loc) · 2.44 KB
/
reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
package x
import (
"bytes"
"errors"
)
var ErrDataLenShort = errors.New("data length is short")
type Reader struct {
pos int
data []byte
}
func NewReaderFromData(data []byte) *Reader {
return &Reader{
data: data,
}
}
func (r *Reader) Pos() int {
return r.pos
}
func (r *Reader) Read1b() uint8 {
v := r.data[r.pos]
r.pos++
return v
}
func (r *Reader) Read2b() uint16 {
v := uint16(r.data[r.pos])
v |= uint16(r.data[r.pos+1]) << 8
r.pos += 2
return v
}
func (r *Reader) Read4b() uint32 {
v := uint32(r.data[r.pos])
v |= uint32(r.data[r.pos+1]) << 8
v |= uint32(r.data[r.pos+2]) << 16
v |= uint32(r.data[r.pos+3]) << 24
r.pos += 4
return v
}
func (r *Reader) MustReadBytes(n int) []byte {
v := r.data[r.pos : r.pos+n]
r.pos += n
return v
}
func (r *Reader) ReadBytes(n int) ([]byte, error) {
if !r.RemainAtLeast(n) {
return nil, ErrDataLenShort
}
v := r.data[r.pos : r.pos+n]
r.pos += n
return v, nil
}
func (r *Reader) ReadBytesWithPad(n int) ([]byte, error) {
total := n + Pad(n)
if !r.RemainAtLeast(total) {
return nil, ErrDataLenShort
}
v := r.data[r.pos : r.pos+n]
r.pos += total
return v, nil
}
func (r *Reader) ReadString(n int) (string, error) {
v, err := r.ReadBytes(n)
if err != nil {
return "", err
}
return string(v), nil
}
func (r *Reader) ReadStrWithPad(n int) (string, error) {
v, err := r.ReadBytesWithPad(n)
if err != nil {
return "", err
}
return string(v), nil
}
func (r *Reader) ReadNulTermStr() string {
idx := bytes.IndexByte(r.data[r.pos:], 0)
var v []byte
if idx == -1 {
v = r.data[r.pos:]
r.pos = len(r.data)
} else {
v = r.data[r.pos : r.pos+idx]
r.pos += idx
}
return string(v)
}
func (r *Reader) ReadBool() bool {
return Uint8ToBool(r.Read1b())
}
func (r *Reader) ReadPad(n int) {
if r.pos+n > len(r.data) {
panic("index out of range")
}
r.pos += n
}
func (r *Reader) Reset() {
r.pos = 0
}
func (r *Reader) RemainAtLeast(n int) bool {
return r.pos+n <= len(r.data)
}
func (r *Reader) RemainAtLeast4b(n int) bool {
return r.RemainAtLeast(n << 2)
}
func (r *Reader) ReadReplyHeader() (data uint8, length uint32) {
r.ReadPad(1)
data = r.Read1b()
// seq
r.ReadPad(2)
// length
length = r.Read4b() // 2
return
}
func (r *Reader) ReadEventHeader() (data uint8, seq uint16) {
r.ReadPad(1)
data = r.Read1b()
// seq
seq = r.Read2b() // 1
return
}