-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
bytes.go
66 lines (57 loc) · 1.31 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
package buffer
import (
"errors"
"io"
"slices"
)
type bytesReader struct {
bs []byte
index int64
}
func newBytesReader(bs []byte) *bytesReader {
return &bytesReader{bs: bs, index: 0}
}
// Read implements the io.Reader interface.
func (r *bytesReader) Read(b []byte) (n int, err error) {
if r.index >= int64(len(r.bs)) {
return 0, io.EOF
}
n = copy(b, r.bs[r.index:])
r.index += int64(n)
return
}
// Seek implements the io.Seeker interface.
func (r *bytesReader) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
r.index = offset
case io.SeekCurrent:
r.index += offset
case io.SeekEnd:
r.index = int64(len(r.bs)) + offset
}
return r.index, nil
}
// ReadAt implements the io.ReaderAt interface.
func (r *bytesReader) ReadAt(b []byte, offset int64) (n int, err error) {
if offset < 0 {
return 0, errors.New("buffer.bytesReader.ReadAt: negative offset")
}
if offset >= int64(len(r.bs)) {
return 0, io.EOF
}
n = copy(b, r.bs[offset:])
if n < len(b) {
err = io.EOF
}
return
}
func (r *bytesReader) insert(offset int64, b byte) {
r.bs = slices.Insert(r.bs, int(offset), b)
}
func (r *bytesReader) delete(offset int64) {
r.bs = slices.Delete(r.bs, int(offset), int(offset+1))
}
func (r *bytesReader) clone() *bytesReader {
return newBytesReader(slices.Clone(r.bs))
}