From 78754a7b23e5fc7a40bd3c450d54a193aaf585b1 Mon Sep 17 00:00:00 2001 From: Laria Carolin Chabowski Date: Mon, 3 Jul 2017 08:10:28 +0200 Subject: Implementing backup methods --- storage/memory_storage.go | 41 +++++++++++++++++++++++++++++++++++++++++ storage/storage.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 storage/memory_storage.go create mode 100644 storage/storage.go (limited to 'storage') 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 +} -- cgit v1.2.3-70-g09d2