aboutsummaryrefslogtreecommitdiff
path: root/storage
diff options
context:
space:
mode:
Diffstat (limited to 'storage')
-rw-r--r--storage/memory_storage.go41
-rw-r--r--storage/storage.go37
2 files changed, 78 insertions, 0 deletions
diff --git a/storage/memory_storage.go b/storage/memory_storage.go
new file mode 100644
index 0000000..0c90981
--- /dev/null
+++ b/storage/memory_storage.go
@@ -0,0 +1,41 @@
+package storage
+
+import (
+ "code.laria.me/petrific/objects"
+)
+
+type MemoryStorage struct {
+ objects map[string][]byte
+ bytype map[objects.ObjectType][]objects.ObjectId
+}
+
+func NewMemoryStorage() Storage {
+ return MemoryStorage{
+ objects: make(map[string][]byte),
+ bytype: make(map[objects.ObjectType][]objects.ObjectId),
+ }
+}
+
+func (ms MemoryStorage) Get(id objects.ObjectId) ([]byte, error) {
+ b, ok := ms.objects[id.String()]
+ if !ok {
+ return nil, ObjectNotFound
+ }
+ return 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()] = 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
+}
diff --git a/storage/storage.go b/storage/storage.go
new file mode 100644
index 0000000..424661c
--- /dev/null
+++ b/storage/storage.go
@@ -0,0 +1,37 @@
+package storage
+
+import (
+ "bytes"
+ "code.laria.me/petrific/objects"
+ "errors"
+)
+
+var (
+ ObjectNotFound = errors.New("Object not found")
+)
+
+type Storage interface {
+ Get(id objects.ObjectId) ([]byte, error)
+ Has(id objects.ObjectId) (bool, error)
+ Set(id objects.ObjectId, typ objects.ObjectType, raw []byte) error
+ List(typ objects.ObjectType) ([]objects.ObjectId, error)
+}
+
+func SetObject(s Storage, o objects.RawObject) (id objects.ObjectId, err error) {
+ buf := new(bytes.Buffer)
+
+ id, err = o.SerializeAndId(buf, objects.OIdAlgoDefault)
+ if err != nil {
+ return
+ }
+
+ ok, err := s.Has(id)
+ if err != nil {
+ return
+ }
+
+ if !ok {
+ err = s.Set(id, o.Type, buf.Bytes())
+ }
+ return
+}