forked from alecthomas/mph
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slicereader_fast.go
44 lines (36 loc) · 1.23 KB
/
slicereader_fast.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
//go:build 386 || amd64 || arm || arm64
// +build 386 amd64 arm arm64
package uint64mph
import (
"encoding/binary"
"github.com/alecthomas/unsafeslice"
)
// Read values and typed vectors from a byte slice without copying where
// possible. This implementation directly references the underlying byte slice
// for array operations, making them essentially zero copy. As the data is
// written in little endian form, this of course means that this will only
// work on little-endian architectures.
type sliceReader struct {
b []byte
start, end uint64
}
func (b *sliceReader) read(size uint64) []byte {
b.start, b.end = b.end, b.end+size
return b.b[b.start:b.end]
}
func (b *sliceReader) ReadUint64Array(n uint64) []uint64 {
if n == 0 {
return []uint64{}
}
b.start, b.end = b.end, b.end+n*8
return unsafeslice.Uint64SliceFromByteSlice(b.b[b.start:b.end])
}
func (b *sliceReader) ReadUint16Array(n uint64) []uint16 {
b.start, b.end = b.end, b.end+n*2
return unsafeslice.Uint16SliceFromByteSlice(b.b[b.start:b.end])
}
// Despite returning a uint64, this actually reads a uint32. All table indices
// and lengths are stored as uint32 values.
func (b *sliceReader) ReadInt() uint64 {
return uint64(binary.LittleEndian.Uint32(b.read(4)))
}