forked from bazil/bazil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
countreader.go
46 lines (40 loc) · 878 Bytes
/
countreader.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
package fstestutil
import (
"encoding/binary"
"io"
)
type CountReader struct {
offset uint64
}
const chunkSize = 4096
const counterSize = 8
const counterAlign = chunkSize - counterSize
var zeroes [chunkSize]byte
func (c *CountReader) Read(p []byte) (n int, err error) {
for len(p) > 0 {
offset := c.offset % chunkSize
if offset < counterAlign {
// distance to next counter location
skip := counterAlign - offset
nn := uint64(copy(p, zeroes[:skip]))
c.offset += nn
offset += nn
n += int(nn)
p = p[nn:]
}
if offset >= chunkSize {
continue
}
if offset >= counterAlign {
align := offset - counterAlign
var num [counterSize]byte
binary.BigEndian.PutUint64(num[:], c.offset/chunkSize)
nn := uint64(copy(p, num[align:]))
c.offset += nn
n += int(nn)
p = p[nn:]
}
}
return n, nil
}
var _ = io.Reader(&CountReader{})