aboutsummaryrefslogtreecommitdiff
path: root/storage/memory/memory.go
blob: dc72f70492b9ec914b6c7cd89c2dadc15cbec40e (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
package memory

import (
	"code.laria.me/petrific/config"
	"code.laria.me/petrific/objects"
	"code.laria.me/petrific/storage"
)

// Memory storage is an in-memory storage. It is rather useless when using petrific, it is mostly used for internal testing.
// But if you want to use the memory storage anyway, you can do that by putting a storage section with the method
// "memory" in your config file
type MemoryStorage struct {
	objects map[string][]byte
	bytype  map[objects.ObjectType][]objects.ObjectId
}

func NewMemoryStorage() storage.Storage {
	return MemoryStorage{
		objects: make(map[string][]byte),
		bytype:  make(map[objects.ObjectType][]objects.ObjectId),
	}
}

func MemoryStorageFromConfig(conf config.Config, name string) (storage.Storage, error) {
	return NewMemoryStorage(), nil
}

func copyBytes(b []byte) []byte {
	c := make([]byte, len(b))
	copy(c, b)
	return c
}

func (ms MemoryStorage) Get(id objects.ObjectId) ([]byte, error) {
	b, ok := ms.objects[id.String()]
	if !ok {
		return nil, storage.ObjectNotFound
	}
	return copyBytes(b), nil
}

func (ms MemoryStorage) Has(id objects.ObjectId) (bool, error) {
	_, ok := ms.objects[id.String()]
	return ok, nil
}

func (ms MemoryStorage) Set(id objects.ObjectId, typ objects.ObjectType, raw []byte) error {
	ms.objects[id.String()] = copyBytes(raw)
	ms.bytype[typ] = append(ms.bytype[typ], id)

	return nil
}

func (ms MemoryStorage) List(typ objects.ObjectType) ([]objects.ObjectId, error) {
	return ms.bytype[typ], nil
}

func (MemoryStorage) Close() error {
	return nil
}