forked from antchfx/xmlquery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcached_reader.go
79 lines (69 loc) · 1.15 KB
/
cached_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
package xmlquery
import (
"bufio"
)
type cachedReader struct {
buffer *bufio.Reader
cache []byte
caching bool
}
func newCachedReader(r *bufio.Reader) *cachedReader {
return &cachedReader{
buffer: r,
cache: make([]byte, 0, 4096),
caching: false,
}
}
func (c *cachedReader) StartCaching() {
c.cache = c.cache[:0]
c.caching = true
}
func (c *cachedReader) ReadByte() (b byte, err error) {
b, err = c.buffer.ReadByte()
if err != nil {
return
}
if c.caching {
c.cacheByte(b)
}
return
}
func (c *cachedReader) Cache() []byte {
return c.cache
}
func (c *cachedReader) CacheWithLimit(n int) []byte {
if n < 1 {
return nil
}
l := len(c.cache)
if n > l {
n = l
}
return c.cache[:n]
}
func (c *cachedReader) StopCaching() {
c.caching = false
}
func (c *cachedReader) Read(p []byte) (int, error) {
n, err := c.buffer.Read(p)
if err != nil {
return n, err
}
if c.caching {
for i := 0; i < n; i++ {
if !c.cacheByte(p[i]) {
break
}
}
}
return n, err
}
func (c *cachedReader) cacheByte(b byte) bool {
n := len(c.cache)
if n == cap(c.cache) {
return false
}
c.cache = c.cache[:n+1]
c.cache[n] = b
return true
}