forked from karrick/goavro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytes.go
358 lines (333 loc) · 10.5 KB
/
bytes.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package goavro
import (
"encoding/hex"
"errors"
"fmt"
"io"
"unicode"
"unicode/utf16"
"unicode/utf8"
)
////////////////////////////////////////
// Binary Decode
////////////////////////////////////////
func bytesNativeFromBinary(buf []byte) (interface{}, []byte, error) {
if len(buf) < 1 {
return nil, nil, fmt.Errorf("cannot decode binary bytes: %s", io.ErrShortBuffer)
}
var decoded interface{}
var err error
if decoded, buf, err = longNativeFromBinary(buf); err != nil {
return nil, nil, fmt.Errorf("cannot decode binary bytes: %s", err)
}
size := decoded.(int64) // always returns int64
if size < 0 {
return nil, nil, fmt.Errorf("cannot decode binary bytes: negative size: %d", size)
}
if size > int64(len(buf)) {
return nil, nil, fmt.Errorf("cannot decode binary bytes: %s", io.ErrShortBuffer)
}
return buf[:size], buf[size:], nil
}
func stringNativeFromBinary(buf []byte) (interface{}, []byte, error) {
d, b, err := bytesNativeFromBinary(buf)
if err != nil {
return nil, nil, fmt.Errorf("cannot decode binary string: %s", err)
}
return string(d.([]byte)), b, nil
}
////////////////////////////////////////
// Binary Encode
////////////////////////////////////////
func bytesBinaryFromNative(buf []byte, datum interface{}) ([]byte, error) {
someBytes, ok := datum.([]byte)
if !ok {
return nil, fmt.Errorf("cannot encode binary bytes: expected: []byte; received: %T", datum)
}
buf, _ = longBinaryFromNative(buf, len(someBytes)) // only fails when given non integer
return append(buf, someBytes...), nil // append datum bytes
}
func stringBinaryFromNative(buf []byte, datum interface{}) ([]byte, error) {
someBytes, ok := datum.(string)
if !ok {
return nil, fmt.Errorf("cannot encode binary bytes: expected: string; received: %T", datum)
}
buf, _ = longBinaryFromNative(buf, len(someBytes)) // only fails when given non integer
return append(buf, someBytes...), nil // append datum bytes
}
////////////////////////////////////////
// Text Decode
////////////////////////////////////////
func bytesNativeFromTextual(buf []byte) (interface{}, []byte, error) {
buflen := len(buf)
if buflen < 2 {
return nil, nil, fmt.Errorf("cannot decode textual bytes: %s", io.ErrShortBuffer)
}
if buf[0] != '"' {
return nil, nil, fmt.Errorf("cannot decode textual bytes: expected initial \"; found: %#U", buf[0])
}
var newBytes []byte
var escaped bool
// Loop through bytes following initial double quote, but note we will
// return immediately when find unescaped double quote.
for i := 1; i < buflen; i++ {
b := buf[i]
if escaped {
escaped = false
if b2, ok := unescapeSpecialJSON(b); ok {
newBytes = append(newBytes, b2)
continue
}
if b == 'u' {
// NOTE: Need at least 4 more bytes to read uint16, but subtract
// 1 because do not want to count the trailing quote and
// subtract another 1 because already consumed u but have yet to
// increment i.
if i > buflen-6 {
return nil, nil, fmt.Errorf("cannot decode textual bytes: %s", io.ErrShortBuffer)
}
// NOTE: Avro bytes represent binary data, and do not
// necessarily represent text. Therefore, Avro bytes are not
// encoded in UTF-16. Each \u is followed by 4 hexidecimal
// digits, the first and second of which must be 0.
v, err := parseUint64FromHexSlice(buf[i+3 : i+5])
if err != nil {
return nil, nil, fmt.Errorf("cannot decode textual bytes: %s", err)
}
i += 4 // absorb 4 characters: one 'u' and three of the digits
newBytes = append(newBytes, byte(v))
continue
}
newBytes = append(newBytes, b)
continue
}
if b == '\\' {
escaped = true
continue
}
if b == '"' {
return newBytes, buf[i+1:], nil
}
newBytes = append(newBytes, b)
}
return nil, nil, fmt.Errorf("cannot decode textual bytes: expected final \"; found: %#U", buf[buflen-1])
}
func stringNativeFromTextual(buf []byte) (interface{}, []byte, error) {
buflen := len(buf)
if buflen < 2 {
return nil, nil, fmt.Errorf("cannot decode textual string: %s", io.ErrShortBuffer)
}
if buf[0] != '"' {
return nil, nil, fmt.Errorf("cannot decode textual string: expected initial \"; found: %#U", buf[0])
}
var newBytes []byte
var escaped bool
// Loop through bytes following initial double quote, but note we will
// return immediately when find unescaped double quote.
for i := 1; i < buflen; i++ {
b := buf[i]
if escaped {
escaped = false
if b2, ok := unescapeSpecialJSON(b); ok {
newBytes = append(newBytes, b2)
continue
}
if b == 'u' {
// NOTE: Need at least 4 more bytes to read uint16, but subtract
// 1 because do not want to count the trailing quote and
// subtract another 1 because already consumed u but have yet to
// increment i.
if i > buflen-6 {
return nil, nil, fmt.Errorf("cannot decode textual string: %s", io.ErrShortBuffer)
}
v, err := parseUint64FromHexSlice(buf[i+1 : i+5])
if err != nil {
return nil, nil, fmt.Errorf("cannot decode textual string: %s", err)
}
i += 4 // absorb 4 characters: one 'u' and three of the digits
nbl := len(newBytes)
newBytes = append(newBytes, []byte{0, 0, 0, 0}...) // grow to make room for UTF-8 encoded rune
r := rune(v)
if utf16.IsSurrogate(r) {
i++ // absorb final hexidecimal digit from previous value
// Expect second half of surrogate pair
if i > buflen-6 || buf[i] != '\\' || buf[i+1] != 'u' {
return nil, nil, errors.New("cannot decode textual string: missing second half of surrogate pair")
}
v, err = parseUint64FromHexSlice(buf[i+2 : i+6])
if err != nil {
return nil, nil, fmt.Errorf("cannot decode textual string: %s", err)
}
i += 5 // absorb 5 characters: two for '\u', and 3 of the 4 digits
// Get code point by combining high and low surrogate bits
r = utf16.DecodeRune(r, rune(v))
}
width := utf8.EncodeRune(newBytes[nbl:], r) // append UTF-8 encoded version of code point
newBytes = newBytes[:nbl+width] // trim off excess bytes
continue
}
newBytes = append(newBytes, b)
continue
}
if b == '\\' {
escaped = true
continue
}
if b == '"' {
return string(newBytes), buf[i+1:], nil
}
newBytes = append(newBytes, b)
}
return nil, nil, fmt.Errorf("cannot decode textual string: expected final \"; found: %x", buf[buflen-1])
}
func parseUint64FromHexSlice(buf []byte) (uint64, error) {
var value uint64
for _, b := range buf {
diff := uint64(b - '0')
if diff < 0 {
return 0, hex.InvalidByteError(b)
}
if diff < 10 {
value = (value << 4) | diff
continue
}
b10 := b + 10
diff = uint64(b10 - 'A')
if diff < 10 {
return 0, hex.InvalidByteError(b)
}
if diff < 16 {
value = (value << 4) | diff
continue
}
diff = uint64(b10 - 'a')
if diff < 10 {
return 0, hex.InvalidByteError(b)
}
if diff < 16 {
value = (value << 4) | diff
continue
}
return 0, hex.InvalidByteError(b)
}
return value, nil
}
func unescapeSpecialJSON(b byte) (byte, bool) {
// NOTE: The following 8 special JSON characters must be escaped:
switch b {
case '"', '\\', '/':
return b, true
case 'b':
return '\b', true
case 'f':
return '\f', true
case 'n':
return '\n', true
case 'r':
return '\r', true
case 't':
return '\t', true
}
return b, false
}
////////////////////////////////////////
// Text Encode
////////////////////////////////////////
func bytesTextualFromNative(buf []byte, datum interface{}) ([]byte, error) {
someBytes, ok := datum.([]byte)
if !ok {
return nil, fmt.Errorf("cannot encode textual bytes: expected: []byte; received: %T", datum)
}
buf = append(buf, '"') // prefix buffer with double quote
for _, b := range someBytes {
if escaped, ok := escapeSpecialJSON(b); ok {
buf = append(buf, escaped...)
continue
}
if r := rune(b); r < utf8.RuneSelf && unicode.IsPrint(r) {
buf = append(buf, b)
continue
}
// This Code Point _could_ be encoded as a single byte, however, it's
// above standard ASCII range (b > 127), therefore must encode using its
// four-byte hexidecimal equivalent, which will always start with the
// high byte 00
buf = appendUnicodeHex(buf, uint16(b))
}
return append(buf, '"'), nil // postfix buffer with double quote
}
func stringTextualFromNative(buf []byte, datum interface{}) ([]byte, error) {
someString, ok := datum.(string)
if !ok {
return nil, fmt.Errorf("cannot encode textual string: expected: string; received: %T", datum)
}
buf = append(buf, '"') // prefix buffer with double quote
for _, r := range someString {
if escaped, ok := escapeSpecialJSON(byte(r)); ok {
buf = append(buf, escaped...)
continue
}
if r < utf8.RuneSelf && unicode.IsPrint(r) {
buf = append(buf, byte(r))
continue
}
// NOTE: Attempt to encode code point as UTF-16 surrogate pair
r1, r2 := utf16.EncodeRune(r)
if r1 != unicode.ReplacementChar || r2 != unicode.ReplacementChar {
// code point does require surrogate pair, and thus two uint16 values
buf = appendUnicodeHex(buf, uint16(r1))
buf = appendUnicodeHex(buf, uint16(r2))
continue
}
// Code Point does not require surrogate pair.
buf = appendUnicodeHex(buf, uint16(r))
}
return append(buf, '"'), nil // postfix buffer with double quote
}
func appendUnicodeHex(buf []byte, v uint16) []byte {
// Start with '\u' prefix:
buf = append(buf, sliceUnicode...)
// And tack on 4 hexidecimal digits:
buf = append(buf, hexDigits[(v&0xF000)>>12])
buf = append(buf, hexDigits[(v&0xF00)>>8])
buf = append(buf, hexDigits[(v&0xF0)>>4])
buf = append(buf, hexDigits[(v&0xF)])
return buf
}
const hexDigits = "0123456789ABCDEF"
func escapeSpecialJSON(b byte) ([]byte, bool) {
// NOTE: The following 8 special JSON characters must be escaped:
switch b {
case '"':
return sliceQuote, true
case '\\':
return sliceBackslash, true
case '/':
return sliceSlash, true
case '\b':
return sliceBackspace, true
case '\f':
return sliceFormfeed, true
case '\n':
return sliceNewline, true
case '\r':
return sliceCarriageReturn, true
case '\t':
return sliceTab, true
}
return nil, false
}
// While slices in Go are never constants, we can initialize them once and reuse
// them many times. We define these slices at library load time and reuse them
// when encoding JSON.
var (
sliceQuote = []byte("\\\"")
sliceBackslash = []byte("\\\\")
sliceSlash = []byte("\\/")
sliceBackspace = []byte("\\b")
sliceFormfeed = []byte("\\f")
sliceNewline = []byte("\\n")
sliceCarriageReturn = []byte("\\r")
sliceTab = []byte("\\t")
sliceUnicode = []byte("\\u")
)