Files
dolt/chunks/chunk.go
T
Rafael Weinstein d1e2aa01f3 Go: ref.Ref -> hash.Hash (#1583)
ref.Ref -> hash.Hash
2016-05-21 11:38:35 -07:00

77 lines
1.9 KiB
Go

package chunks
import (
"bytes"
"github.com/attic-labs/noms/d"
"github.com/attic-labs/noms/hash"
)
// Chunk is a unit of stored data in noms
type Chunk struct {
r hash.Hash
data []byte
}
var EmptyChunk = Chunk{}
func (c Chunk) Hash() hash.Hash {
return c.r
}
func (c Chunk) Data() []byte {
return c.data
}
func (c Chunk) IsEmpty() bool {
return len(c.data) == 0
}
// NewChunk creates a new Chunk backed by data. This means that the returned Chunk has ownership of this slice of memory.
func NewChunk(data []byte) Chunk {
r := hash.FromData(data)
return Chunk{r, data}
}
// NewChunkWithHash creates a new chunk with a known hash. The hash is not re-calculated or verified. This should obviously only be used in cases where the caller already knows the specified hash is correct.
func NewChunkWithHash(r hash.Hash, data []byte) Chunk {
return Chunk{r, data}
}
// ChunkWriter wraps an io.WriteCloser, additionally providing the ability to grab the resulting Chunk for all data written through the interface. Calling Chunk() or Close() on an instance disallows further writing.
type ChunkWriter struct {
buffer *bytes.Buffer
c Chunk
}
func NewChunkWriter() *ChunkWriter {
b := &bytes.Buffer{}
return &ChunkWriter{
buffer: b,
}
}
func (w *ChunkWriter) Write(data []byte) (int, error) {
d.Chk.NotNil(w.buffer, "Write() cannot be called after Hash() or Close().")
size, err := w.buffer.Write(data)
d.Chk.NoError(err)
return size, nil
}
// Chunk() closes the writer and returns the resulting Chunk.
func (w *ChunkWriter) Chunk() Chunk {
d.Chk.NoError(w.Close())
return w.c
}
// Close() closes computes the hash and Puts it into the ChunkSink Note: The Write() method never returns an error. Instead, like other noms interfaces, errors are reported via panic.
func (w *ChunkWriter) Close() error {
if w.buffer == nil {
return nil
}
w.c = NewChunk(w.buffer.Bytes())
w.buffer = nil
return nil
}