-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathreader.go
556 lines (506 loc) · 11.9 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
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package dedup
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
)
// A Reader will decode a deduplicated stream and
// return the data as it was encoded.
// Use Close when done to release resources.
type Reader interface {
io.ReadCloser
io.WriterTo
// MaxMem returns the *maximum* memory required to decode the stream.
MaxMem() int
}
// IndexedReader gives access to internal information on
// block sizes available on indexed streams.
type IndexedReader interface {
Reader
// Blocksizes will return the sizes of each block.
// Will be available if an index was provided.
BlockSizes() []int
}
type reader struct {
streamReader
blocks []*rblock
}
type streamReader struct {
size int
maxLength uint64 // Maxmimum backreference count
curBlock int
curData []byte
ready chan *rblock
closeReader chan struct{}
readerClosed chan struct{}
}
// rblock contains read information about a single block
type rblock struct {
data []byte
readData int
first int // Index of first occurrence
last int // Index of last occurrence
offset int64 // Expected offset in data file (format 1)
err error // Read error?
}
func (r *rblock) String() string {
if r == nil {
return "<nil>"
}
return fmt.Sprintf("{Read:%d; [%d:%d], offset:%d}", r.readData, r.first, r.last, r.offset)
}
var ErrUnknownFormat = errors.New("unknown index format")
// NewReader returns a reader that will decode the supplied index and data stream.
//
// This is compatible content from the NewWriter function.
// The function will decode the index before returning.
//
// When you are done with the Reader, use Close to release resources.
func NewReader(index io.Reader, blocks io.Reader) (IndexedReader, error) {
f := &reader{streamReader: streamReader{
ready: make(chan *rblock, 8), // Read up to 8 blocks ahead
closeReader: make(chan struct{}, 0),
readerClosed: make(chan struct{}, 0),
curBlock: 0,
}}
idx := bufio.NewReader(index)
format, err := binary.ReadUvarint(idx)
if err != nil {
return nil, err
}
switch format {
case 1:
err = f.readFormat1(idx)
default:
err = ErrUnknownFormat
}
go f.blockReader(blocks)
return f, err
}
// NewStreamReader returns a reader that will decode the supplied data stream.
//
// This is compatible content from the NewStreamWriter function.
//
// When you are done with the Reader, use Close to release resources.
func NewStreamReader(in io.Reader) (Reader, error) {
f := &streamReader{
ready: make(chan *rblock, 8), // Read up to 8 blocks ahead
closeReader: make(chan struct{}, 0),
readerClosed: make(chan struct{}, 0),
curBlock: 0,
}
br := bufio.NewReader(in)
format, err := binary.ReadUvarint(br)
if err != nil {
return nil, err
}
switch format {
case 2:
err = f.readFormat2(br)
if err != nil {
return nil, err
}
default:
return nil, ErrUnknownFormat
}
go f.streamReader(br)
return f, nil
}
// NewSeekRead returns a reader that will decode the supplied index and data stream.
//
// This is compatible content from the NewWriter function.
//
// No blocks will be kept in memory, but the block data input must be seekable.
// The function will decode the index before returning.
//
// When you are done with the Reader, use Close to release resources.
func NewSeekReader(index io.Reader, blocks io.ReadSeeker) (IndexedReader, error) {
f := &reader{streamReader: streamReader{
ready: make(chan *rblock, 8), // Read up to 8 blocks ahead
closeReader: make(chan struct{}, 0),
readerClosed: make(chan struct{}, 0),
curBlock: 0,
maxLength: 8, // We have 8 blocks readahead.
}}
idx := bufio.NewReader(index)
format, err := binary.ReadUvarint(idx)
if err != nil {
return nil, err
}
switch format {
case 1:
err = f.readFormat1(idx)
default:
err = ErrUnknownFormat
}
go f.seekReader(blocks)
return f, err
}
// readFormat1 will read the index of format 1
// and prepare decoding
func (f *reader) readFormat1(idx io.ByteReader) error {
size, err := binary.ReadUvarint(idx)
if err != nil {
return err
}
f.size = int(size)
// Insert empty block 0
f.blocks = append(f.blocks, nil)
i := 0
var foffset int64
// Read blocks
for {
i++
offset, err := binary.ReadUvarint(idx)
if err != nil {
return err
}
switch offset {
// new block
case 0:
r, err := binary.ReadUvarint(idx)
if err != nil {
return err
}
if r > size {
return fmt.Errorf("invalid size for block %d, %d > %d", i, r, size)
}
f.blocks = append(f.blocks, &rblock{first: i, last: i, readData: int(size - r), offset: foffset})
foffset += int64(size - r)
// Last block
case math.MaxUint64:
r, err := binary.ReadUvarint(idx)
if err != nil {
return err
}
if r > size {
return fmt.Errorf("invalid size for block %d, %d > %d", i, r, size)
}
f.blocks = append(f.blocks, &rblock{readData: int(size - r), offset: foffset})
foffset += int64(size - r)
// Continuation should be 0
r, err = binary.ReadUvarint(idx)
if err != nil {
return err
}
if r != 0 {
return fmt.Errorf("invalid continuation, should be 0, was %d", r)
}
return nil
// Deduplicated block
default:
pos := len(f.blocks) - int(offset)
if pos <= 0 || pos >= len(f.blocks) {
return fmt.Errorf("invalid offset encountered at block %d, offset was %d", len(f.blocks), offset)
}
// Update last position.
org := f.blocks[pos]
org.last = i
f.blocks = append(f.blocks, org)
}
}
}
// readFormat2 will read the header data of format 2
// and stop at the first block.
func (f *streamReader) readFormat2(rd io.ByteReader) error {
size, err := binary.ReadUvarint(rd)
if err != nil {
return err
}
if size < MinBlockSize {
return ErrSizeTooSmall
}
f.size = int(size)
maxLength, err := binary.ReadUvarint(rd)
if err != nil {
return err
}
if maxLength < 1 {
return ErrMaxMemoryTooSmall
}
f.maxLength = maxLength
return nil
}
// Read will read from the input stream and return the
// deduplicated data.
func (f *streamReader) Read(b []byte) (int, error) {
read := 0
for len(b) > 0 {
// Read next
if len(f.curData) == 0 {
f.curBlock++
next, ok := <-f.ready
if !ok {
return read, io.EOF
}
if next.err != nil {
return read, next.err
}
f.curData = next.data
// We don't want to keep it, if this is the last block
if f.curBlock == next.last {
next.data = nil
}
if len(f.curData) == 0 {
continue
}
}
n := copy(b, f.curData)
read += n
b = b[n:]
f.curData = f.curData[n:]
}
return read, nil
}
// WriteTo writes data to w until there's no more data to write or when an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (f *streamReader) WriteTo(w io.Writer) (int64, error) {
written := int64(0)
for {
next, ok := <-f.ready
if !ok {
return written, io.EOF
}
if next.err != nil {
return written, next.err
}
f.curBlock++
f.curData = next.data
// We don't want to keep it, if this is the last block
if f.curBlock == next.last {
next.data = nil
}
n, err := w.Write(f.curData)
written += int64(n)
if err != nil {
return written, err
}
}
}
// MaxMem returns the estimated maximum RAM usage needed to
// unpack this content.
func (f *streamReader) MaxMem() int {
if f.maxLength > 0 {
return int(f.maxLength) * f.size
}
return -1
}
// MaxMem returns the estimated maximum RAM usage needed to
// unpack this content.
func (f *reader) MaxMem() int {
i := 1 // Current block
curUse := 0
maxUse := 0
for {
b := f.blocks[i]
if b.first == i {
curUse += b.readData
}
if curUse > maxUse {
maxUse = curUse
}
if b.last == i {
curUse -= b.readData
}
i++
// We read them all
if i == len(f.blocks) {
break
}
}
return maxUse
}
func (f *reader) BlockSizes() []int {
if len(f.blocks) < 2 {
return nil
}
ret := make([]int, len(f.blocks)-1)
for i, bl := range f.blocks[1:] {
ret[i] = bl.readData
}
return ret
}
// blockReader will read format 1 blocks and deliver them
// to the ready channel.
// The function will return if the stream is finished,
// or an error occurs
func (f *reader) blockReader(in io.Reader) {
defer close(f.readerClosed)
defer close(f.ready)
i := 1 // Current block
totalRead := 0
for {
b := f.blocks[i]
// Read it?
if len(b.data) != b.readData {
b.data = make([]byte, b.readData)
n, err := io.ReadFull(in, b.data)
if err != nil {
b.err = err
} else if n != b.readData {
b.err = io.ErrUnexpectedEOF
}
totalRead += n
}
// Send or close
select {
case <-f.closeReader:
return
case f.ready <- b:
}
// Exit because of an error
if b.err != nil {
return
}
i++
// We read them all
if i == len(f.blocks) {
return
}
}
}
// streamReader will read blocks from a single stream
// and deliver them to the "ready" channel.
// The function will return if an error occurs or
// the stream is finished.
func (f *streamReader) streamReader(stream *bufio.Reader) {
defer close(f.readerClosed)
defer close(f.ready)
totalRead := 0
// Create backreference buffers
blocks := make([][]byte, f.maxLength)
for i := range blocks {
blocks[i] = make([]byte, f.size)
}
i := uint64(1) // Current block
for {
b := &rblock{}
lastBlock := false
b.err = func() error {
offset, err := binary.ReadUvarint(stream)
if err != nil {
return err
}
// Read it?
if offset == 0 || offset == math.MaxUint64 {
s, err := binary.ReadUvarint(stream)
if err != nil {
return err
}
size := f.size - int(s)
if offset == math.MaxUint64 && size == 0 {
lastBlock = true
return nil
}
if size > f.size || size <= 0 {
return fmt.Errorf("invalid size encountered at block %d, size was %d", i, size)
}
b.data = make([]byte, size)
n, err := io.ReadFull(stream, b.data)
if err != nil {
return err
} else if n != len(b.data) {
return io.ErrUnexpectedEOF
}
totalRead += n
if offset == math.MaxUint64 {
lastBlock = true
}
} else {
if offset > f.maxLength {
return fmt.Errorf("invalid offset encountered at block %d, offset was %d", i, offset)
}
pos := i - offset
if pos <= 0 {
return fmt.Errorf("invalid offset encountered at block %d, offset was %d", i, offset)
}
src := blocks[pos%f.maxLength]
b.data = src
}
blocks[i%f.maxLength] = b.data
return nil
}()
// Read continuation
if lastBlock {
r, err := binary.ReadUvarint(stream)
if err != nil {
b.err = err
}
if r != 0 {
b.err = fmt.Errorf("invalid continuation, should be 0, was %d", r)
}
}
// Send or close
select {
case <-f.closeReader:
return
case f.ready <- b:
}
// Exit because of an error
if b.err != nil || lastBlock {
return
}
i++
}
}
// seekReader will read format 1 blocks and deliver them
// to the ready channel.
// The function will return if the stream is finished,
// or an error occurs
func (f *reader) seekReader(in io.ReadSeeker) {
defer close(f.readerClosed)
defer close(f.ready)
i := 1 // Current block
var foffset int64
for {
// Copy b, we are modifying it.
b := *f.blocks[i]
// Seek to offset if needed, and
if b.offset != foffset {
_, err := in.Seek(b.offset, 0)
if err != nil {
b.err = err
}
}
if b.err == nil {
b.data = make([]byte, b.readData)
n, err := io.ReadFull(in, b.data)
if err != nil {
b.err = err
} else if n != b.readData {
b.err = io.ErrUnexpectedEOF
}
foffset = b.offset + int64(n)
}
// Always release the memory of this block
b.last = i
// Send or close
select {
case <-f.closeReader:
return
case f.ready <- &b:
}
// Exit because of an error
if b.err != nil {
return
}
i++
// We read them all
if i == len(f.blocks) {
return
}
}
}
// Close the reader and shut down the running goroutines.
func (f *streamReader) Close() error {
select {
case <-f.readerClosed:
case f.closeReader <- struct{}{}:
<-f.readerClosed
}
return nil
}