-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchunk.go
94 lines (83 loc) · 2.04 KB
/
chunk.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
package chunk
import (
"encoding/binary"
"errors"
"io"
"io/ioutil"
)
// Reader is a struct representing a data chunk. Its reader is shared with the
// container but convenience methods are provided.
type Reader struct {
ID [4]byte
Size int
R io.Reader
Pos int
}
// Done makes sure the entire Reader was read.
func (ch *Reader) Done() {
if !ch.IsFullyRead() {
ch.drain()
}
}
// Read implements the reader interface
func (ch *Reader) Read(p []byte) (n int, err error) {
if ch == nil || ch.R == nil {
return 0, errors.New("nil Reader/reader pointer")
}
n, err = ch.R.Read(p)
ch.Pos += n
return n, err
}
// ReadLE reads the Little Endian Reader data into the passed struct
func (ch *Reader) ReadLE(dst interface{}) error {
return ch.readWithByteOrder(dst, binary.LittleEndian)
}
// ReadBE reads the Big Endian Reader data into the passed struct
func (ch *Reader) ReadBE(dst interface{}) error {
return ch.readWithByteOrder(dst, binary.BigEndian)
}
// ReadByte reads and returns a single byte
func (ch *Reader) ReadByte() (byte, error) {
if ch.IsFullyRead() {
return 0, io.EOF
}
var r byte
err := ch.ReadLE(&r)
return r, err
}
// IsFullyRead checks if we're finished reading the Reader
func (ch *Reader) IsFullyRead() bool {
if ch == nil || ch.R == nil {
return true
}
return ch.Size <= ch.Pos
}
// Jump jumps ahead in the Reader
func (ch *Reader) Jump(bytesAhead int) error {
var err error
var n int64
if bytesAhead > 0 {
n, err = io.CopyN(ioutil.Discard, ch.R, int64(bytesAhead))
ch.Pos += int(n)
}
return err
}
func (ch *Reader) readWithByteOrder(dst interface{}, byteOrder binary.ByteOrder) error {
if ch == nil || ch.R == nil {
return errors.New("nil Reader/reader pointer")
}
if ch.IsFullyRead() {
return io.EOF
}
ch.Pos += binary.Size(dst)
return binary.Read(ch.R, byteOrder, dst)
}
// You are probably looking to call Done() instead!
func (ch *Reader) drain() error {
bytesAhead := ch.Size - ch.Pos
if bytesAhead > 0 {
_, err := io.CopyN(ioutil.Discard, ch.R, int64(bytesAhead))
return err
}
return nil
}