| 1 |
package plumbing |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"io" |
| 6 |
) |
| 7 |
|
| 8 |
// MemoryObject on memory Object implementation |
| 9 |
type MemoryObject struct { |
| 10 |
t ObjectType |
| 11 |
h Hash |
| 12 |
cont []byte |
| 13 |
sz int64 |
| 14 |
} |
| 15 |
|
| 16 |
// Hash returns the object Hash, the hash is calculated on-the-fly the first |
| 17 |
// time it's called, in all subsequent calls the same Hash is returned even |
| 18 |
// if the type or the content have changed. The Hash is only generated if the |
| 19 |
// size of the content is exactly the object size. |
| 20 |
func (o *MemoryObject) Hash() Hash { |
| 21 |
if o.h == ZeroHash && int64(len(o.cont)) == o.sz { |
| 22 |
o.h = ComputeHash(o.t, o.cont) |
| 23 |
} |
| 24 |
|
| 25 |
return o.h |
| 26 |
} |
| 27 |
|
| 28 |
// Type returns the ObjectType |
| 29 |
func (o *MemoryObject) Type() ObjectType { return o.t } |
| 30 |
|
| 31 |
// SetType sets the ObjectType |
| 32 |
func (o *MemoryObject) SetType(t ObjectType) { o.t = t } |
| 33 |
|
| 34 |
// Size returns the size of the object |
| 35 |
func (o *MemoryObject) Size() int64 { return o.sz } |
| 36 |
|
| 37 |
// SetSize set the object size, a content of the given size should be written |
| 38 |
// afterwards |
| 39 |
func (o *MemoryObject) SetSize(s int64) { o.sz = s } |
| 40 |
|
| 41 |
// Reader returns an io.ReadCloser used to read the object's content. |
| 42 |
// |
| 43 |
// For a MemoryObject, this reader is seekable. |
| 44 |
func (o *MemoryObject) Reader() (io.ReadCloser, error) { |
| 45 |
return nopCloser{bytes.NewReader(o.cont)}, nil |
| 46 |
} |
| 47 |
|
| 48 |
// Writer returns a ObjectWriter used to write the object's content. |
| 49 |
func (o *MemoryObject) Writer() (io.WriteCloser, error) { |
| 50 |
return o, nil |
| 51 |
} |
| 52 |
|
| 53 |
func (o *MemoryObject) Write(p []byte) (n int, err error) { |
| 54 |
o.cont = append(o.cont, p...) |
| 55 |
o.sz = int64(len(o.cont)) |
| 56 |
|
| 57 |
return len(p), nil |
| 58 |
} |
| 59 |
|
| 60 |
// Close releases any resources consumed by the object when it is acting as a |
| 61 |
// ObjectWriter. |
| 62 |
func (o *MemoryObject) Close() error { return nil } |
| 63 |
|
| 64 |
// nopCloser exposes the extra methods of bytes.Reader while nopping Close(). |
| 65 |
// |
| 66 |
// This allows clients to attempt seeking in a cached Blob's Reader. |
| 67 |
type nopCloser struct { |
| 68 |
*bytes.Reader |
| 69 |
} |
| 70 |
|
| 71 |
// Close does nothing. |
| 72 |
func (nc nopCloser) Close() error { return nil } |