forked from mikkyang/id3-go
/
reader.go
87 lines (73 loc) · 1.84 KB
/
reader.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
// Copyright 2013 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package encodedbytes
import (
"errors"
"io"
)
// Reader is a helper for Reading frame bytes
type Reader struct {
data []byte
index int // current Reading index
}
func (r *Reader) Read(b []byte) (n int, err error) {
if len(b) == 0 {
return 0, nil
}
if r.index >= len(r.data) {
return 0, io.EOF
}
n = copy(b, r.data[r.index:])
r.index += n
return
}
func (r *Reader) ReadByte() (b byte, err error) {
if r.index >= len(r.data) {
return 0, io.EOF
}
b = r.data[r.index]
r.index++
return
}
func (r *Reader) ReadNumBytes(n int) ([]byte, error) {
if n <= 0 {
return []byte{}, nil
}
if r.index+n > len(r.data) {
return []byte{}, io.EOF
}
b := make([]byte, n)
_, err := r.Read(b)
return b, err
}
// Read a number of bytes and cast to a string
func (r *Reader) ReadNumBytesString(n int) (string, error) {
b, err := r.ReadNumBytes(n)
return string(b), err
}
// Read until the end of the data
func (r *Reader) ReadRest() ([]byte, error) {
return r.ReadNumBytes(len(r.data) - r.index)
}
// Read until the end of the data and cast to a string
func (r *Reader) ReadRestString(encoding byte) (string, error) {
b, err := r.ReadRest()
if err != nil {
return "", err
}
return Decoders[encoding].ConvertString(string(b))
}
// Read a null terminated string of specified encoding
func (r *Reader) ReadNullTermString(encoding byte) (string, error) {
atIndex, afterIndex := nullIndex(r.data[r.index:], encoding)
b, err := r.ReadNumBytes(afterIndex)
if err != nil {
return "", err
}
if -1 == atIndex {
return "", errors.New("could not read null terminated string")
}
return Decoders[encoding].ConvertString(string(b[:atIndex]))
}
func NewReader(b []byte) *Reader { return &Reader{b, 0} }