aboutsummaryrefslogtreecommitdiff
path: root/chunk.go
blob: 92e3563fd1da99fc0fd44f79ca1952d3d90ef889 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main

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

type ChunkReader interface {
	io.Reader
	io.ByteReader
}

type Chunk interface {
	Reader() ChunkReader
}

type StoredChunk interface {
	Chunk
	Id() *ChunkId
}

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)
}

func NewLoadedChunk(id *ChunkId, value []byte) *LoadedChunk {
	return &LoadedChunk{id: id, value: value}
}

type LoadedChunk struct {
	id    *ChunkId
	value []byte
}

func (c *LoadedChunk) Id() *ChunkId {
	return c.id
}

func (c *LoadedChunk) Reader() ChunkReader {
	// log.Printf("Chunk %d: Reading from in-memory value\n", c.id)
	return bytes.NewReader(c.value)
}

func NewChunkFile(repo *Repo, id *ChunkId) *ChunkFile {
	return &ChunkFile{repo: repo, id: id}
}

type ChunkFile struct {
	repo *Repo
	id   *ChunkId
}

func (c *ChunkFile) Id() *ChunkId {
	return c.id
}

func (c *ChunkFile) Reader() ChunkReader {
	// log.Printf("Chunk %d: Reading from file\n", c.id)
	return c.id.Reader(c.repo.path)
}

func NewTempChunk(value []byte) *TempChunk {
	return &TempChunk{value: value}
}

type TempChunk struct {
	value []byte
}

func (c *TempChunk) Reader() ChunkReader {
	return bytes.NewReader(c.value)
}