Debian Codegraph @

stack/reader.go

raw
1 // Copyright 2020 Marc-Antoine Ruel. All rights reserved.
2 // Use of this source code is governed under the Apache License, Version 2.0
3 // that can be found in the LICENSE file.
4
5 package stack
6
7 import (
8 "bytes"
9 "errors"
10 "io"
11 )
12
13 var (
14 errBufferFull = errors.New("buffer full")
15 )
16
17 type reader struct {
18 buf [16 * 1024]byte
19 rd io.Reader
20 r, w int
21 err error
22 }
23
24 // fill reads a new chunk into the buffer.
25 func (r *reader) fill() {
26 // Slide existing data to beginning.
27 if r.r > 0 {
28 copy(r.buf[:], r.buf[r.r:r.w])
29 r.w -= r.r
30 r.r = 0
31 }
32 if r.w >= len(r.buf) {
33 panic("tried to fill full buffer")
34 }
35 // Read new data: try a limited number of times.
36 for i := 100; i > 0; i-- {
37 n, err := r.rd.Read(r.buf[r.w:])
38 if n < 0 {
39 panic("reader returned negative count from Read")
40 }
41 r.w += n
42 if err != nil {
43 r.err = err
44 return
45 }
46 if n > 0 {
47 return
48 }
49 }
50 r.err = io.ErrNoProgress
51 }
52
53 func (r *reader) buffered() []byte {
54 return r.buf[r.r:r.w]
55 }
56
57 func (r *reader) readSlice() ([]byte, error) {
58 for s := 0; ; r.fill() {
59 if i := bytes.IndexByte(r.buf[r.r+s:r.w], '\n'); i >= 0 {
60 i += s
61 line := r.buf[r.r : r.r+i+1]
62 r.r += i + 1
63 return line, nil
64 }
65 if r.err != nil {
66 line := r.buf[r.r:r.w]
67 r.r = r.w
68 err := r.err
69 r.err = nil
70 return line, err
71 }
72 if r.w-r.r == len(r.buf) {
73 r.r = r.w
74 return r.buf[:], errBufferFull
75 }
76 s = r.w - r.r
77 }
78 }
79
80 // readLine is our own implementation of ReadBytes().
81 //
82 // We try to use readSlice() as much as we can but we need to tolerate if an
83 // input line is longer than the buffer specified at Reader creation. Not using
84 // the more complicated slice of slices that Reader.ReadBytes() uses since it
85 // should not happen often here. Instead bootstrap the memory allocation by
86 // starting with 4x buffer size, which should get most cases with a single
87 // allocation.
88 func (r *reader) readLine() ([]byte, error) {
89 var d []byte
90 for {
91 f, err := r.readSlice()
92 if err != errBufferFull {
93 if d == nil {
94 return f, err
95 }
96 return append(d, f...), err
97 }
98 if d == nil {
99 d = make([]byte, 0, len(f)*4)
100 }
101 d = append(d, f...)
102 }
103 }