-
Notifications
You must be signed in to change notification settings - Fork 0
/
peek.go
104 lines (78 loc) · 1.7 KB
/
peek.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
package gbuf
import (
"fmt"
"io"
)
// Peek reads from the Buffer `b`, however it does not advance the buffer's offset after the items are read
func Peek[T any](p []T, b *Buffer[T]) (n int, err error) {
if b == nil {
return 0, nil
}
if b.empty() {
// Buffer is empty, reset to recover space.
b.Reset()
if len(p) == 0 {
return 0, nil
}
return 0, io.EOF
}
n = copy(p, b.buf[b.off:])
return n, nil
}
// PeekFrom is just like Peek, but it reads from the buffer starting at offset `idx`
func PeekFrom[T any](idx int, p []T, b *Buffer[T]) (n int, err error) {
if b == nil {
return 0, nil
}
if idx < 0 || idx >= len(b.buf) {
return 0, ErrPeekBufferIndexOutOfBounds
}
if b.empty() {
// Buffer is empty, reset to recover space.
b.Reset()
if len(p) == 0 {
return 0, nil
}
return 0, io.EOF
}
n = copy(p, b.buf[idx:])
return n, nil
}
// PeekRange is just like Peek, but it reads from the buffer starting at offset `from` until offset `to`
func PeekRange[T any](from, to int, p []T, b *Buffer[T]) (n int, err error) {
if b == nil {
return 0, nil
}
if from == to {
return 0, nil
}
var (
invert bool
ln = len(p)
)
if from < 0 || from >= len(b.buf) {
return 0, fmt.Errorf("%w: from value: %d", ErrIndexOutOfBounds, from)
}
if to < 0 || to >= len(b.buf) {
return 0, fmt.Errorf("%w: to value: %d", ErrIndexOutOfBounds, to)
}
if from > to {
invert = true
to, from = from, to
}
if b.empty() {
// Buffer is empty, reset to recover space.
b.Reset()
if ln == 0 {
return 0, nil
}
return 0, io.EOF
}
n = copy(p, b.buf[to:from])
if invert {
for i, j := 0, ln-1; i < ln/2; i, j = i+1, j-1 {
p[i], p[j] = p[j], p[i]
}
}
return n, nil
}