1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package cryptobyte
19
20
21
22 type String []byte
23
24
25
26 func (s *String) read(n int) []byte {
27 if len(*s) < n || n < 0 {
28 return nil
29 }
30 v := (*s)[:n]
31 *s = (*s)[n:]
32 return v
33 }
34
35
36 func (s *String) Skip(n int) bool {
37 return s.read(n) != nil
38 }
39
40
41
42 func (s *String) ReadUint8(out *uint8) bool {
43 v := s.read(1)
44 if v == nil {
45 return false
46 }
47 *out = uint8(v[0])
48 return true
49 }
50
51
52
53 func (s *String) ReadUint16(out *uint16) bool {
54 v := s.read(2)
55 if v == nil {
56 return false
57 }
58 *out = uint16(v[0])<<8 | uint16(v[1])
59 return true
60 }
61
62
63
64 func (s *String) ReadUint24(out *uint32) bool {
65 v := s.read(3)
66 if v == nil {
67 return false
68 }
69 *out = uint32(v[0])<<16 | uint32(v[1])<<8 | uint32(v[2])
70 return true
71 }
72
73
74
75 func (s *String) ReadUint32(out *uint32) bool {
76 v := s.read(4)
77 if v == nil {
78 return false
79 }
80 *out = uint32(v[0])<<24 | uint32(v[1])<<16 | uint32(v[2])<<8 | uint32(v[3])
81 return true
82 }
83
84 func (s *String) readUnsigned(out *uint32, length int) bool {
85 v := s.read(length)
86 if v == nil {
87 return false
88 }
89 var result uint32
90 for i := 0; i < length; i++ {
91 result <<= 8
92 result |= uint32(v[i])
93 }
94 *out = result
95 return true
96 }
97
98 func (s *String) readLengthPrefixed(lenLen int, outChild *String) bool {
99 lenBytes := s.read(lenLen)
100 if lenBytes == nil {
101 return false
102 }
103 var length uint32
104 for _, b := range lenBytes {
105 length = length << 8
106 length = length | uint32(b)
107 }
108 v := s.read(int(length))
109 if v == nil {
110 return false
111 }
112 *outChild = v
113 return true
114 }
115
116
117
118 func (s *String) ReadUint8LengthPrefixed(out *String) bool {
119 return s.readLengthPrefixed(1, out)
120 }
121
122
123
124
125 func (s *String) ReadUint16LengthPrefixed(out *String) bool {
126 return s.readLengthPrefixed(2, out)
127 }
128
129
130
131
132 func (s *String) ReadUint24LengthPrefixed(out *String) bool {
133 return s.readLengthPrefixed(3, out)
134 }
135
136
137
138 func (s *String) ReadBytes(out *[]byte, n int) bool {
139 v := s.read(n)
140 if v == nil {
141 return false
142 }
143 *out = v
144 return true
145 }
146
147
148
149 func (s *String) CopyBytes(out []byte) bool {
150 n := len(out)
151 v := s.read(n)
152 if v == nil {
153 return false
154 }
155 return copy(out, v) == n
156 }
157
158
159 func (s String) Empty() bool {
160 return len(s) == 0
161 }
162
View as plain text