This repository has been archived by the owner on May 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
chunk.go
166 lines (135 loc) · 2.29 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package scat
import (
"bytes"
"io"
"io/ioutil"
"sync"
"github.com/Roman2K/scat/checksum"
)
type Chunk struct {
num int
data Data
hash checksum.Hash
targetSize int
meta *Meta
}
func NewChunk(num int, data Data) *Chunk {
if data == nil {
data = BytesData(nil)
}
return &Chunk{
num: num,
data: data,
}
}
func (c *Chunk) Num() int {
return c.num
}
func (c *Chunk) Data() Data {
return c.data
}
func (c *Chunk) WithData(d Data) *Chunk {
dup := *c
dup.data = d
if dup.meta != nil {
dup.meta = c.meta.dup()
}
return &dup
}
func (c *Chunk) Hash() checksum.Hash {
return c.hash
}
func (c *Chunk) SetHash(h checksum.Hash) {
c.hash = h
}
func (c *Chunk) TargetSize() int {
return c.targetSize
}
func (c *Chunk) SetTargetSize(s int) {
c.targetSize = s
}
func (c *Chunk) Meta() *Meta {
if c.meta == nil {
c.meta = newMeta()
}
return c.meta
}
type Meta struct {
m metaMap
mu sync.RWMutex
}
type metaMap map[interface{}]interface{}
func newMeta() *Meta {
return &Meta{m: make(metaMap)}
}
func (m *Meta) Get(k interface{}) interface{} {
m.mu.RLock()
defer m.mu.RUnlock()
return m.m[k]
}
func (m *Meta) Set(k, v interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
m.m[k] = v
}
func (m *Meta) dup() (dup *Meta) {
dup = newMeta()
m.mu.RLock()
defer m.mu.RUnlock()
for k, v := range m.m {
dup.m[k] = v
}
return
}
type Data interface {
Reader() io.Reader
Bytes() ([]byte, error)
}
type Sizer interface {
Size() int
}
type sizedData interface {
Data
Sizer
}
type BytesData []byte
var _ sizedData = BytesData{}
func (b BytesData) Reader() io.Reader {
return bytes.NewReader([]byte(b))
}
func (b BytesData) Bytes() ([]byte, error) {
return []byte(b), nil
}
func (b BytesData) Size() int {
return len(b)
}
type readerData struct {
r io.Reader
onceChan chan struct{}
}
func NewReaderData(r io.Reader) Data {
return readerData{
r: r,
onceChan: make(chan struct{}, 1),
}
}
func (r readerData) Reader() (reader io.Reader) {
r.once(func() {
reader = r.r
})
return
}
func (r readerData) Bytes() (b []byte, err error) {
r.once(func() {
b, err = ioutil.ReadAll(r.r)
})
return
}
func (r readerData) once(fn func()) {
select {
case r.onceChan <- struct{}{}:
fn()
default:
panic("reader data can only be read once")
}
}