-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchunk.go
102 lines (91 loc) · 2.22 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
95
96
97
98
99
100
101
102
package aiff
import (
"encoding/binary"
"errors"
"io"
"io/ioutil"
)
// Chunk is a struct representing a data chunk
// the reader is shared with the container but convenience methods
// are provided.
// The reader always starts at the beggining of the data.
// SSND chunk is the sound chunk
// Chunk specs:
// http://www.onicos.com/staff/iz/formats/aiff.html
// AFAn seems to be an OS X specific chunk, meaning & format TBD
type Chunk struct {
ID [4]byte
Size int
R io.Reader
Pos int
}
// Done makes sure the entire chunk was read.
func (ch *Chunk) Done() {
if !ch.IsFullyRead() {
ch.drain()
}
}
func (ch *Chunk) drain() error {
bytesAhead := ch.Size - ch.Pos
if bytesAhead > 0 {
_, err := io.CopyN(ioutil.Discard, ch.R, int64(bytesAhead))
return err
}
return nil
}
// Read implements the reader interface
func (ch *Chunk) Read(p []byte) (n int, err error) {
if ch == nil || ch.R == nil {
return 0, errors.New("nil chunk/reader pointer")
}
n, err = ch.R.Read(p)
ch.Pos += n
return n, err
}
func (ch *Chunk) readWithByteOrder(dst interface{}, byteOrder binary.ByteOrder) error {
if ch == nil || ch.R == nil {
return errors.New("nil chunk/reader pointer")
}
if ch.IsFullyRead() {
return io.EOF
}
ch.Pos += binary.Size(dst)
return binary.Read(ch.R, byteOrder, dst)
}
// ReadLE reads the Little Endian chunk data into the passed struct
func (ch *Chunk) ReadLE(dst interface{}) error {
return ch.readWithByteOrder(dst, binary.LittleEndian)
}
// ReadBE reads the Big Endian chunk data into the passed struct
func (ch *Chunk) ReadBE(dst interface{}) error {
return ch.readWithByteOrder(dst, binary.BigEndian)
}
// ReadByte reads and returns a single byte
func (ch *Chunk) 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 chunk
func (ch *Chunk) IsFullyRead() bool {
if ch == nil || ch.R == nil {
return true
}
return ch.Size <= ch.Pos
}
// Jump jumps ahead in the chunk
func (ch *Chunk) Jump(bytesAhead int) error {
if ch.R == nil {
return io.EOF
}
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
}