Debian Codegraph @

codec/reader.go

raw symbols SCIP
1 // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
2 // Use of this source code is governed by a MIT license found in the LICENSE file.
3
4 package codec
5
6 import "io"
7
8 // decReader abstracts the reading source, allowing implementations that can
9 // read from an io.Reader or directly off a byte slice with zero-copying.
10 type decReader interface {
11 // readx will return a view of the []byte if decoding from a []byte, OR
12 // read into the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR
13 // create a new []byte and read into that
14 readx(n uint) []byte
15
16 readb([]byte)
17
18 readn1() byte
19 readn2() [2]byte
20 // readn3 will read 3 bytes into the top-most elements of a 4-byte array
21 readn3() [4]byte
22 readn4() [4]byte
23 readn8() [8]byte
24 // readn1eof() (v uint8, eof bool)
25
26 // // read up to 8 bytes at a time
27 // readn(num uint8) (v [8]byte)
28
29 numread() uint // number of bytes read
30
31 // skip any whitespace characters, and return the first non-matching byte
32 skipWhitespace() (token byte)
33
34 // jsonReadNum will include last read byte in first element of slice,
35 // and continue numeric characters until it sees a non-numeric char
36 // or EOF. If it sees a non-numeric character, it will unread that.
37 jsonReadNum() []byte
38
39 // jsonReadAsisChars will read json plain characters (anything but " or \)
40 // and return a slice terminated by a non-json asis character.
41 jsonReadAsisChars() []byte
42
43 // skip will skip any byte that matches, and return the first non-matching byte
44 // skip(accept *bitset256) (token byte)
45
46 // readTo will read any byte that matches, stopping once no-longer matching.
47 // readTo(accept *bitset256) (out []byte)
48
49 // readUntil will read, only stopping once it matches the 'stop' byte (which it excludes).
50 readUntil(stop byte) (out []byte)
51 }
52
53 // ------------------------------------------------
54
55 type unreadByteStatus uint8
56
57 // unreadByteStatus goes from
58 // undefined (when initialized) -- (read) --> canUnread -- (unread) --> canRead ...
59 const (
60 unreadByteUndefined unreadByteStatus = iota
61 unreadByteCanRead
62 unreadByteCanUnread
63 )
64
65 // --------------------
66
67 type ioDecReaderCommon struct {
68 r io.Reader // the reader passed in
69
70 n uint // num read
71
72 l byte // last byte
73 ls unreadByteStatus // last byte status
74
75 b [6]byte // tiny buffer for reading single bytes
76
77 blist *bytesFreelist
78
79 bufr []byte // buffer for readTo/readUntil
80 }
81
82 func (z *ioDecReaderCommon) reset(r io.Reader, blist *bytesFreelist) {
83 z.blist = blist
84 z.r = r
85 z.ls = unreadByteUndefined
86 z.l, z.n = 0, 0
87 z.bufr = z.blist.check(z.bufr, 256)
88 }
89
90 func (z *ioDecReaderCommon) numread() uint {
91 return z.n
92 }
93
94 // ------------------------------------------
95
96 // ioDecReader is a decReader that reads off an io.Reader.
97 //
98 // It also has a fallback implementation of ByteScanner if needed.
99 type ioDecReader struct {
100 ioDecReaderCommon
101
102 br io.ByteScanner
103
104 x [64 + 48]byte // for: get struct field name, swallow valueTypeBytes, etc
105 }
106
107 func (z *ioDecReader) reset(r io.Reader, blist *bytesFreelist) {
108 z.ioDecReaderCommon.reset(r, blist)
109
110 z.br, _ = r.(io.ByteScanner)
111 }
112
113 func (z *ioDecReader) Read(p []byte) (n int, err error) {
114 if len(p) == 0 {
115 return
116 }
117 var firstByte bool
118 if z.ls == unreadByteCanRead {
119 z.ls = unreadByteCanUnread
120 p[0] = z.l
121 if len(p) == 1 {
122 n = 1
123 return
124 }
125 firstByte = true
126 p = p[1:]
127 }
128 n, err = z.r.Read(p)
129 if n > 0 {
130 if err == io.EOF && n == len(p) {
131 err = nil // read was successful, so postpone EOF (till next time)
132 }
133 z.l = p[n-1]
134 z.ls = unreadByteCanUnread
135 }
136 if firstByte {
137 n++
138 }
139 return
140 }
141
142 func (z *ioDecReader) ReadByte() (c byte, err error) {
143 if z.br != nil {
144 c, err = z.br.ReadByte()
145 if err == nil {
146 z.l = c
147 z.ls = unreadByteCanUnread
148 }
149 return
150 }
151
152 n, err := z.Read(z.b[:1])
153 if n == 1 {
154 c = z.b[0]
155 if err == io.EOF {
156 err = nil // read was successful, so postpone EOF (till next time)
157 }
158 }
159 return
160 }
161
162 func (z *ioDecReader) UnreadByte() (err error) {
163 if z.br != nil {
164 err = z.br.UnreadByte()
165 if err == nil {
166 z.ls = unreadByteCanRead
167 }
168 return
169 }
170
171 switch z.ls {
172 case unreadByteCanUnread:
173 z.ls = unreadByteCanRead
174 case unreadByteCanRead:
175 err = errDecUnreadByteLastByteNotRead
176 case unreadByteUndefined:
177 err = errDecUnreadByteNothingToRead
178 default:
179 err = errDecUnreadByteUnknown
180 }
181 return
182 }
183
184 func (z *ioDecReader) readn2() (bs [2]byte) {
185 z.readb(bs[:])
186 return
187 }
188
189 func (z *ioDecReader) readn3() (bs [4]byte) {
190 z.readb(bs[1:])
191 return
192 }
193
194 func (z *ioDecReader) readn4() (bs [4]byte) {
195 z.readb(bs[:])
196 return
197 }
198
199 func (z *ioDecReader) readn8() (bs [8]byte) {
200 z.readb(bs[:])
201 return
202 }
203
204 func (z *ioDecReader) readx(n uint) (bs []byte) {
205 if n == 0 {
206 return
207 }
208 if n < uint(len(z.x)) {
209 bs = z.x[:n]
210 } else {
211 bs = make([]byte, n)
212 }
213 _, err := readFull(z.r, bs)
214 halt.onerror(err)
215 z.n += uint(len(bs))
216 return
217 }
218
219 func (z *ioDecReader) readb(bs []byte) {
220 if len(bs) == 0 {
221 return
222 }
223 _, err := readFull(z.r, bs)
224 halt.onerror(err)
225 z.n += uint(len(bs))
226 }
227
228 func (z *ioDecReader) readn1() (b uint8) {
229 b, err := z.ReadByte()
230 halt.onerror(err)
231 z.n++
232 return
233 }
234
235 func (z *ioDecReader) readn1eof() (b uint8, eof bool) {
236 b, err := z.ReadByte()
237 if err == nil {
238 z.n++
239 } else if err == io.EOF {
240 eof = true
241 } else {
242 halt.onerror(err)
243 }
244 return
245 }
246
247 func (z *ioDecReader) jsonReadNum() (bs []byte) {
248 z.unreadn1()
249 z.bufr = z.bufr[:0]
250 LOOP:
251 i, eof := z.readn1eof()
252 if eof {
253 return z.bufr
254 }
255 if isNumberChar(i) {
256 z.bufr = append(z.bufr, i)
257 goto LOOP
258 }
259 z.unreadn1()
260 return z.bufr
261 }
262
263 func (z *ioDecReader) jsonReadAsisChars() (bs []byte) {
264 z.bufr = z.bufr[:0]
265 LOOP:
266 i := z.readn1()
267 z.bufr = append(z.bufr, i)
268 if i == '"' || i == '\\' {
269 return z.bufr
270 }
271 goto LOOP
272 }
273
274 func (z *ioDecReader) skipWhitespace() (token byte) {
275 LOOP:
276 token = z.readn1()
277 if isWhitespaceChar(token) {
278 goto LOOP
279 }
280 return
281 }
282
283 func (z *ioDecReader) readUntil(stop byte) []byte {
284 z.bufr = z.bufr[:0]
285 LOOP:
286 token := z.readn1()
287 z.bufr = append(z.bufr, token)
288 if token == stop {
289 return z.bufr[:len(z.bufr)-1]
290 }
291 goto LOOP
292 }
293
294 func (z *ioDecReader) unreadn1() {
295 err := z.UnreadByte()
296 halt.onerror(err)
297 z.n--
298 }
299
300 // ------------------------------------
301
302 type bufioDecReader struct {
303 ioDecReaderCommon
304
305 c uint // cursor
306 buf []byte
307 }
308
309 func (z *bufioDecReader) reset(r io.Reader, bufsize int, blist *bytesFreelist) {
310 z.ioDecReaderCommon.reset(r, blist)
311 z.c = 0
312 if cap(z.buf) < bufsize {
313 z.buf = blist.get(bufsize)
314 } else {
315 z.buf = z.buf[:0]
316 }
317 }
318
319 func (z *bufioDecReader) readb(p []byte) {
320 var n = uint(copy(p, z.buf[z.c:]))
321 z.n += n
322 z.c += n
323 if len(p) != int(n) {
324 z.readbFill(p, n, true, false)
325 }
326 }
327
328 func readbFillHandleErr(err error, must, eof bool) (isEOF bool) {
329 if err == io.EOF {
330 isEOF = true
331 }
332 if must && !(eof && isEOF) {
333 halt.onerror(err)
334 }
335 return
336 }
337
338 func (z *bufioDecReader) readbFill(p0 []byte, n uint, must, eof bool) (isEOF bool, err error) {
339 // at this point, there's nothing in z.buf to read (z.buf is fully consumed)
340 var p []byte
341 if p0 != nil {
342 p = p0[n:]
343 }
344 var n2 uint
345 if len(p) > cap(z.buf) {
346 n2, err = readFull(z.r, p)
347 if err != nil {
348 isEOF = readbFillHandleErr(err, must, eof)
349 return
350 }
351 n += n2
352 z.n += n2
353 // always keep last byte in z.buf
354 z.buf = z.buf[:1]
355 z.buf[0] = p[len(p)-1]
356 z.c = 1
357 return
358 }
359 // z.c is now 0, and len(p) <= cap(z.buf)
360 var n1 int
361 LOOP:
362 // for len(p) > 0 && z.err == nil {
363 z.buf = z.buf[0:cap(z.buf)]
364 n1, err = z.r.Read(z.buf)
365 n2 = uint(n1)
366 if n2 == 0 && err != nil {
367 isEOF = readbFillHandleErr(err, must, eof)
368 return
369 }
370 err = nil
371 z.buf = z.buf[:n2]
372 z.c = 0
373 if len(p) > 0 {
374 n2 = uint(copy(p, z.buf))
375 z.c = n2
376 n += n2
377 z.n += n2
378 p = p[n2:]
379 if len(p) > 0 {
380 goto LOOP
381 }
382 if z.c == 0 {
383 z.buf = z.buf[:1]
384 z.buf[0] = p[len(p)-1]
385 z.c = 1
386 }
387 }
388 return
389 }
390
391 func (z *bufioDecReader) readn1() (b byte) {
392 if z.c >= uint(len(z.buf)) {
393 z.readbFill(nil, 0, true, false)
394 }
395 b = z.buf[z.c]
396 z.c++
397 z.n++
398 return
399 }
400
401 func (z *bufioDecReader) readn1eof() (b byte, eof bool) {
402 if z.c >= uint(len(z.buf)) {
403 eof, _ = z.readbFill(nil, 0, true, true)
404 if eof {
405 return
406 }
407 }
408 b = z.buf[z.c]
409 z.c++
410 z.n++
411 return
412 }
413
414 func (z *bufioDecReader) unreadn1() {
415 if z.c == 0 {
416 halt.onerror(errDecUnreadByteNothingToRead)
417 }
418 z.c--
419 z.n--
420 }
421
422 func (z *bufioDecReader) readn2() (bs [2]byte) {
423 z.readb(bs[:])
424 return
425 }
426
427 func (z *bufioDecReader) readn3() (bs [4]byte) {
428 z.readb(bs[1:])
429 return
430 }
431
432 func (z *bufioDecReader) readn4() (bs [4]byte) {
433 z.readb(bs[:])
434 return
435 }
436
437 func (z *bufioDecReader) readn8() (bs [8]byte) {
438 z.readb(bs[:])
439 return
440 }
441
442 func (z *bufioDecReader) readx(n uint) (bs []byte) {
443 if n == 0 {
444 // return
445 } else if z.c+n <= uint(len(z.buf)) {
446 bs = z.buf[z.c : z.c+n]
447 z.n += n
448 z.c += n
449 } else {
450 bs = make([]byte, n)
451 // n no longer used - can reuse
452 n = uint(copy(bs, z.buf[z.c:]))
453 z.n += n
454 z.c += n
455 z.readbFill(bs, n, true, false)
456 }
457 return
458 }
459
460 func (z *bufioDecReader) jsonReadNum() (bs []byte) {
461 z.unreadn1()
462 z.bufr = z.bufr[:0]
463 LOOP:
464 i, eof := z.readn1eof()
465 if eof {
466 return z.bufr
467 }
468 if isNumberChar(i) {
469 z.bufr = append(z.bufr, i)
470 goto LOOP
471 }
472 z.unreadn1()
473 return z.bufr
474 }
475
476 func (z *bufioDecReader) jsonReadAsisChars() (bs []byte) {
477 z.bufr = z.bufr[:0]
478 LOOP:
479 i := z.readn1()
480 z.bufr = append(z.bufr, i)
481 if i == '"' || i == '\\' {
482 return z.bufr
483 }
484 goto LOOP
485 }
486
487 func (z *bufioDecReader) skipWhitespace() (token byte) {
488 i := z.c
489 LOOP:
490 if i < uint(len(z.buf)) {
491 // inline z.skipLoopFn(i) and refactor, so cost is within inline budget
492 token = z.buf[i]
493 i++
494 if isWhitespaceChar(token) {
495 goto LOOP
496 }
497 z.n += i - 2 - z.c
498 z.c = i
499 return
500 }
501 return z.skipFillWhitespace()
502 }
503
504 func (z *bufioDecReader) skipFillWhitespace() (token byte) {
505 z.n += uint(len(z.buf)) - z.c
506 var i, n2 int
507 var err error
508 for {
509 z.c = 0
510 z.buf = z.buf[0:cap(z.buf)]
511 n2, err = z.r.Read(z.buf)
512 if n2 == 0 {
513 halt.onerror(err)
514 }
515 z.buf = z.buf[:n2]
516 for i, token = range z.buf {
517 if !isWhitespaceChar(token) {
518 z.n += (uint(i) - z.c) - 1
519 z.loopFn(uint(i + 1))
520 return
521 }
522 }
523 z.n += uint(n2)
524 }
525 }
526
527 func (z *bufioDecReader) loopFn(i uint) {
528 z.c = i
529 }
530
531 func (z *bufioDecReader) readUntil(stop byte) (out []byte) {
532 i := z.c
533 LOOP:
534 if i < uint(len(z.buf)) {
535 if z.buf[i] == stop {
536 z.n += (i - z.c) - 1
537 i++
538 out = z.buf[z.c:i]
539 z.c = i
540 goto FINISH
541 }
542 i++
543 goto LOOP
544 }
545 out = z.readUntilFill(stop)
546 FINISH:
547 return out[:len(out)-1]
548 }
549
550 func (z *bufioDecReader) readUntilFill(stop byte) []byte {
551 z.bufr = z.bufr[:0]
552 z.n += uint(len(z.buf)) - z.c
553 z.bufr = append(z.bufr, z.buf[z.c:]...)
554 for {
555 z.c = 0
556 z.buf = z.buf[0:cap(z.buf)]
557 n1, err := z.r.Read(z.buf)
558 if n1 == 0 {
559 halt.onerror(err)
560 }
561 n2 := uint(n1)
562 z.buf = z.buf[:n2]
563 for i, token := range z.buf {
564 if token == stop {
565 z.n += (uint(i) - z.c) - 1
566 z.bufr = append(z.bufr, z.buf[z.c:i+1]...)
567 z.loopFn(uint(i + 1))
568 return z.bufr
569 }
570 }
571 z.bufr = append(z.bufr, z.buf...)
572 z.n += n2
573 }
574 }
575
576 // ------------------------------------
577
578 // bytesDecReader is a decReader that reads off a byte slice with zero copying
579 //
580 // Note: we do not try to convert index'ing out of bounds to an io.EOF.
581 // instead, we let it bubble up to the exported Encode/Decode method
582 // and recover it as an io.EOF.
583 //
584 // see panicValToErr(...) function in helper.go.
585 type bytesDecReader struct {
586 b []byte // data
587 c uint // cursor
588 }
589
590 func (z *bytesDecReader) reset(in []byte) {
591 z.b = in[:len(in):len(in)] // reslicing must not go past capacity
592 z.c = 0
593 }
594
595 func (z *bytesDecReader) numread() uint {
596 return z.c
597 }
598
599 // Note: slicing from a non-constant start position is more expensive,
600 // as more computation is required to decipher the pointer start position.
601 // However, we do it only once, and it's better than reslicing both z.b and return value.
602
603 func (z *bytesDecReader) readx(n uint) (bs []byte) {
604 x := z.c + n
605 bs = z.b[z.c:x]
606 z.c = x
607 return
608 }
609
610 func (z *bytesDecReader) readb(bs []byte) {
611 copy(bs, z.readx(uint(len(bs))))
612 }
613
614 // MARKER: do not use this - as it calls into memmove (as the size of data to move is unknown)
615 // func (z *bytesDecReader) readnn(bs []byte, n uint) {
616 // x := z.c
617 // copy(bs, z.b[x:x+n])
618 // z.c += n
619 // }
620
621 // func (z *bytesDecReader) readn(num uint8) (bs [8]byte) {
622 // x := z.c + uint(num)
623 // copy(bs[:], z.b[z.c:x]) // slice z.b completely, so we get bounds error if past
624 // z.c = x
625 // return
626 // }
627
628 // func (z *bytesDecReader) readn1() uint8 {
629 // z.c++
630 // return z.b[z.c-1]
631 // }
632
633 func (z *bytesDecReader) readn1() (v uint8) {
634 v = z.b[z.c]
635 z.c++
636 return
637 }
638
639 // MARKER: for readn{2,3,4,8}, ensure you slice z.b completely so we get bounds error if past end.
640
641 func (z *bytesDecReader) readn2() (bs [2]byte) {
642 // copy(bs[:], z.b[z.c:z.c+2])
643 bs[1] = z.b[z.c+1]
644 bs[0] = z.b[z.c]
645 z.c += 2
646 return
647 }
648
649 func (z *bytesDecReader) readn3() (bs [4]byte) {
650 // copy(bs[1:], z.b[z.c:z.c+3])
651 bs = okBytes3(z.b[z.c : z.c+3])
652 z.c += 3
653 return
654 }
655
656 func (z *bytesDecReader) readn4() (bs [4]byte) {
657 // copy(bs[:], z.b[z.c:z.c+4])
658 bs = okBytes4(z.b[z.c : z.c+4])
659 z.c += 4
660 return
661 }
662
663 func (z *bytesDecReader) readn8() (bs [8]byte) {
664 // copy(bs[:], z.b[z.c:z.c+8])
665 bs = okBytes8(z.b[z.c : z.c+8])
666 z.c += 8
667 return
668 }
669
670 func (z *bytesDecReader) jsonReadNum() []byte {
671 z.c--
672 i := z.c
673 LOOP:
674 if i < uint(len(z.b)) && isNumberChar(z.b[i]) {
675 i++
676 goto LOOP
677 }
678 z.c, i = i, z.c
679 return z.b[i:z.c]
680 }
681
682 func (z *bytesDecReader) jsonReadAsisChars() []byte {
683 i := z.c
684 LOOP:
685 token := z.b[i]
686 i++
687 if token == '"' || token == '\\' {
688 z.c, i = i, z.c
689 return z.b[i:z.c]
690 }
691 goto LOOP
692 }
693
694 func (z *bytesDecReader) skipWhitespace() (token byte) {
695 i := z.c
696 LOOP:
697 token = z.b[i]
698 if isWhitespaceChar(token) {
699 i++
700 goto LOOP
701 }
702 z.c = i + 1
703 return
704 }
705
706 func (z *bytesDecReader) readUntil(stop byte) (out []byte) {
707 i := z.c
708 LOOP:
709 if z.b[i] == stop {
710 out = z.b[z.c:i]
711 z.c = i + 1
712 return
713 }
714 i++
715 goto LOOP
716 }
717
718 // --------------
719
720 type decRd struct {
721 mtr bool // is maptype a known type?
722 str bool // is slicetype a known type?
723
724 be bool // is binary encoding
725 js bool // is json handle
726 jsms bool // is json handle, and MapKeyAsString
727 cbor bool // is cbor handle
728
729 bytes bool // is bytes reader
730 bufio bool // is this a bufioDecReader?
731
732 rb bytesDecReader
733 ri *ioDecReader
734 bi *bufioDecReader
735
736 decReader
737 }
738
739 // From out benchmarking, we see the following in terms of performance:
740 //
741 // - interface calls
742 // - branch that can inline what it calls
743 //
744 // the if/else-if/else block is expensive to inline.
745 // Each node of this construct costs a lot and dominates the budget.
746 // Best to only do an if fast-path else block (so fast-path is inlined).
747 // This is irrespective of inlineExtraCallCost set in $GOROOT/src/cmd/compile/internal/gc/inl.go
748 //
749 // In decRd methods below, we delegate all IO functions into their own methods.
750 // This allows for the inlining of the common path when z.bytes=true.
751 // Go 1.12+ supports inlining methods with up to 1 inlined function (or 2 if no other constructs).
752 //
753 // However, up through Go 1.13, decRd's readXXX, skip and unreadXXX methods are not inlined.
754 // Consequently, there is no benefit to do the xxxIO methods for decRd at this time.
755 // Instead, we have a if/else-if/else block so that IO calls do not have to jump through
756 // a second unnecessary function call.
757 //
758 // If golang inlining gets better and bytesDecReader methods can be inlined,
759 // then we can revert to using these 2 functions so the bytesDecReader
760 // methods are inlined and the IO paths call out to a function.
761 //
762 // decRd is designed to embed a decReader, and then re-implement some of the decReader
763 // methods using a conditional branch. We only override the ones that have a bytes version
764 // that is small enough to be inlined. We use ./run.sh -z to check.
765 // Right now, only numread and readn1 can be inlined.
766
767 func (z *decRd) numread() uint {
768 if z.bytes {
769 return z.rb.numread()
770 } else if z.bufio {
771 return z.bi.numread()
772 } else {
773 return z.ri.numread()
774 }
775 }
776
777 func (z *decRd) readn1() (v uint8) {
778 if z.bytes {
779 // MARKER: manually inline, else this function is not inlined.
780 // Keep in sync with bytesDecReader.readn1
781 // return z.rb.readn1()
782 v = z.rb.b[z.rb.c]
783 z.rb.c++
784 } else {
785 v = z.readn1IO()
786 }
787 return
788 }
789 func (z *decRd) readn1IO() uint8 {
790 if z.bufio {
791 return z.bi.readn1()
792 }
793 return z.ri.readn1()
794 }
795
796 type devNullReader struct{}
797
798 func (devNullReader) Read(p []byte) (int, error) { return 0, io.EOF }
799 func (devNullReader) Close() error { return nil }
800
801 func readFull(r io.Reader, bs []byte) (n uint, err error) {
802 var nn int
803 for n < uint(len(bs)) && err == nil {
804 nn, err = r.Read(bs[n:])
805 if nn > 0 {
806 if err == io.EOF {
807 // leave EOF for next time
808 err = nil
809 }
810 n += uint(nn)
811 }
812 }
813 // do not do this below - it serves no purpose
814 // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
815 return
816 }
817
818 var _ decReader = (*decRd)(nil)