splitting.go 718 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10
package chunk

import (
	"io"

	"github.com/jbenet/go-ipfs/util"
)

var log = util.Logger("chunk")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
var DefaultSplitter = &SizeSplitter{Size: 1024 * 512}
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

type BlockSplitter interface {
	Split(r io.Reader) chan []byte
}

type SizeSplitter struct {
	Size int
}

func (ss *SizeSplitter) Split(r io.Reader) chan []byte {
	out := make(chan []byte)
	go func() {
		defer close(out)
		for {
			chunk := make([]byte, ss.Size)
			nread, err := r.Read(chunk)
			if err != nil {
				if err == io.EOF {
					if nread > 0 {
						out <- chunk[:nread]
					}
					return
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
				log.Errorf("Block split error: %s", err)
36 37 38 39 40 41 42 43 44 45
				return
			}
			if nread < ss.Size {
				chunk = chunk[:nread]
			}
			out <- chunk
		}
	}()
	return out
}