-
Notifications
You must be signed in to change notification settings - Fork 7
/
Blocks.go
62 lines (53 loc) · 1.44 KB
/
Blocks.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
package resource
import (
"bytes"
"io"
)
// Block is one set of bytes stored in a resource.
// The interpretation of the bytes is dependent on the content type of the resource.
type Block []byte
// Blocks is a list of blocks in memory.
type Blocks struct {
data [][]byte
}
// BlocksFrom returns a blocks instance from given data.
func BlocksFrom(data [][]byte) Blocks {
return Blocks{data: data}
}
// BlockCount returns the number of available blocks.
func (blocks Blocks) BlockCount() int {
return len(blocks.data)
}
// BlockRaw returns the raw byte slice stored in the identified block.
func (blocks Blocks) BlockRaw(index int) ([]byte, error) {
available := len(blocks.data)
if (index < 0) || (index >= available) {
return nil, ErrBlockNotFound(index, available)
}
return blocks.data[index], nil
}
// Block returns the reader for the identified block.
// Each call returns a new reader instance.
func (blocks Blocks) Block(index int) (io.Reader, error) {
raw, err := blocks.BlockRaw(index)
if err != nil {
return nil, err
}
return bytes.NewBuffer(raw), nil
}
// Set the data of all the blocks.
func (blocks *Blocks) Set(data [][]byte) {
blocks.data = data
}
// SetBlock sets the data of the identified block.
func (blocks *Blocks) SetBlock(index int, data []byte) {
if index < 0 {
return
}
if index >= len(blocks.data) {
newData := make([][]byte, index+1)
copy(newData, blocks.data)
blocks.data = newData
}
blocks.data[index] = data
}