| 1 |
package gitobj |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"sync" |
| 8 |
|
| 9 |
"github.com/git-lfs/gitobj/v2/errors" |
| 10 |
) |
| 11 |
|
| 12 |
// memoryStorer is an implementation of the storer interface that holds data for |
| 13 |
// the object database in memory. |
| 14 |
type memoryStorer struct { |
| 15 |
// mu guards reads and writes to the map "fs" below. |
| 16 |
mu *sync.Mutex |
| 17 |
// fs maps a hex-encoded SHA to a bytes.Buffer wrapped in a no-op closer |
| 18 |
// type. |
| 19 |
fs map[string]*bufCloser |
| 20 |
} |
| 21 |
|
| 22 |
// newMemoryStorer initializes a new memoryStorer instance with the given |
| 23 |
// initial set. |
| 24 |
// |
| 25 |
// A value of "nil" is acceptable and indicates that no entries shall be added |
| 26 |
// to the memory storer at/during construction time. |
| 27 |
func newMemoryStorer(m map[string]io.ReadWriter) *memoryStorer { |
| 28 |
fs := make(map[string]*bufCloser, len(m)) |
| 29 |
for n, rw := range m { |
| 30 |
fs[n] = &bufCloser{rw} |
| 31 |
} |
| 32 |
|
| 33 |
return &memoryStorer{ |
| 34 |
mu: new(sync.Mutex), |
| 35 |
fs: fs, |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
// Store implements the storer.Store function and copies the data given in "r" |
| 40 |
// into an object entry in the memory. If an object given by that SHA "sha" is |
| 41 |
// already indexed in the database, Store will panic(). |
| 42 |
func (ms *memoryStorer) Store(sha []byte, r io.Reader) (n int64, err error) { |
| 43 |
ms.mu.Lock() |
| 44 |
defer ms.mu.Unlock() |
| 45 |
|
| 46 |
key := fmt.Sprintf("%x", sha) |
| 47 |
|
| 48 |
ms.fs[key] = &bufCloser{new(bytes.Buffer)} |
| 49 |
return io.Copy(ms.fs[key], r) |
| 50 |
} |
| 51 |
|
| 52 |
// Open implements the storer.Open function, and returns a io.ReadWriteCloser |
| 53 |
// for the given SHA. If a reader for the given SHA does not exist an error will |
| 54 |
// be returned. |
| 55 |
func (ms *memoryStorer) Open(sha []byte) (f io.ReadCloser, err error) { |
| 56 |
ms.mu.Lock() |
| 57 |
defer ms.mu.Unlock() |
| 58 |
|
| 59 |
key := fmt.Sprintf("%x", sha) |
| 60 |
if _, ok := ms.fs[key]; !ok { |
| 61 |
return nil, errors.NoSuchObject(sha) |
| 62 |
} |
| 63 |
return ms.fs[key], nil |
| 64 |
} |
| 65 |
|
| 66 |
// Close closes the memory storer. |
| 67 |
func (ms *memoryStorer) Close() error { |
| 68 |
return nil |
| 69 |
} |
| 70 |
|
| 71 |
// IsCompressed returns true, because the memory storer returns compressed data. |
| 72 |
func (ms *memoryStorer) IsCompressed() bool { |
| 73 |
return true |
| 74 |
} |
| 75 |
|
| 76 |
// bufCloser wraps a type satisfying the io.ReadWriter interface with a no-op |
| 77 |
// Close() function, thus implementing the io.ReadWriteCloser composite |
| 78 |
// interface. |
| 79 |
type bufCloser struct { |
| 80 |
io.ReadWriter |
| 81 |
} |
| 82 |
|
| 83 |
// Close implements io.Closer, and returns nothing. |
| 84 |
func (b *bufCloser) Close() error { return nil } |