aboutsummaryrefslogtreecommitdiff
path: root/chunk.go
blob: 0746fde144fd0ce75bf3505c960e7285e6272811 (plain)
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
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"path"
)

type ChunkId struct {
	Ver int
	Idx uint64
}

func (i *ChunkId) Reader(repo string) ChunkReader {
	p := path.Join(repo, fmt.Sprintf(versionFmt, i.Ver), chunksName, fmt.Sprintf(chunkIdFmt, i.Idx))
	f, err := os.Open(p)
	if err != nil {
		log.Printf("Cannot open chunk %s\n", p)
	}
	return bufio.NewReaderSize(f, chunkSize)
}

type ChunkReader interface {
	io.Reader
	io.ByteReader
}

type Chunk struct {
	Repo  *Repo
	Id    *ChunkId
	Value []byte
}

func (c *Chunk) Read(buff []byte) (int, error) {
	r, err := c.Reader()
	if err != nil {
		return 0, err
	}
	return r.Read(buff)
}

func (c *Chunk) Reader() (ChunkReader, error) {
	if c.Value != nil {
		return bytes.NewReader(c.Value), nil
	}
	if c.Id != nil {
		return c.Id.Reader(c.Repo.path), nil
	}
	return nil, &ChunkError{"Uninitialized chunk"}
}

func (c *Chunk) isStored() bool {
	return c.Id != nil
}

type ChunkError struct {
	err string
}

func (e *ChunkError) Error() string {
	return fmt.Sprintf("Chunk error: %s", e.err)
}