memory.go 1.36 KB
Newer Older
Eric Myhre's avatar
Eric Myhre committed
1 2 3 4 5 6 7
package storage

import (
	"bytes"
	"fmt"
	"io"

tavit ohanian's avatar
tavit ohanian committed
8
	ld "gitlab.dms3.io/ld/go-ld-prime"
Eric Myhre's avatar
Eric Myhre committed
9 10
)

tavit ohanian's avatar
tavit ohanian committed
11
// Memory is a simple in-memory storage for data indexed by ld.Link.
Eric Myhre's avatar
Eric Myhre committed
12 13 14
// (It's little more than a map -- in fact, the map is exported,
// and you can poke it directly.)
//
tavit ohanian's avatar
tavit ohanian committed
15 16
// The OpenRead method conforms to ld.BlockReadOpener,
// and the OpenWrite method conforms to ld.BlockWriteOpener.
Eric Myhre's avatar
Eric Myhre committed
17 18 19 20 21 22 23 24 25
// Therefore it's easy to use in a LinkSystem like this:
//
//		store := storage.Memory{}
//		lsys.StorageReadOpener = (&store).OpenRead
//		lsys.StorageWriteOpener = (&store).OpenWrite
//
// This storage is mostly expected to be used for testing and demos,
// and as an example of how you can implement and integrate your own storage systems.
type Memory struct {
tavit ohanian's avatar
tavit ohanian committed
26
	Bag map[ld.Link][]byte
Eric Myhre's avatar
Eric Myhre committed
27 28 29 30 31 32
}

func (store *Memory) beInitialized() {
	if store.Bag != nil {
		return
	}
tavit ohanian's avatar
tavit ohanian committed
33
	store.Bag = make(map[ld.Link][]byte)
Eric Myhre's avatar
Eric Myhre committed
34 35
}

tavit ohanian's avatar
tavit ohanian committed
36
func (store *Memory) OpenRead(lnkCtx ld.LinkContext, lnk ld.Link) (io.Reader, error) {
Eric Myhre's avatar
Eric Myhre committed
37 38 39 40 41 42 43 44
	store.beInitialized()
	data, exists := store.Bag[lnk]
	if !exists {
		return nil, fmt.Errorf("404") // FIXME this needs a standard error type
	}
	return bytes.NewReader(data), nil
}

tavit ohanian's avatar
tavit ohanian committed
45
func (store *Memory) OpenWrite(lnkCtx ld.LinkContext) (io.Writer, ld.BlockWriteCommitter, error) {
Eric Myhre's avatar
Eric Myhre committed
46 47
	store.beInitialized()
	buf := bytes.Buffer{}
tavit ohanian's avatar
tavit ohanian committed
48
	return &buf, func(lnk ld.Link) error {
Eric Myhre's avatar
Eric Myhre committed
49 50 51 52
		store.Bag[lnk] = buf.Bytes()
		return nil
	}, nil
}