~whereswaldon/forest-go

1af783e4999d674d2fabfd6724c206065e546d96 — Chris Waldon 2 years ago a9e7c6c
Finish implementing simple in-memory node store
2 files changed, 50 insertions(+), 6 deletions(-)

M store.go
M store_test.go
M store.go => store.go +44 -5
@@ 1,6 1,10 @@
package forest

import "git.sr.ht/~whereswaldon/forest-go/fields"
import (
	"fmt"

	"git.sr.ht/~whereswaldon/forest-go/fields"
)

type Store interface {
	Size() (int, error)


@@ 10,24 14,59 @@ type Store interface {
}

type MemoryStore struct {
	Items map[string]Node
}

func NewMemoryStore() *MemoryStore {
	return &MemoryStore{}
	return &MemoryStore{make(map[string]Node)}
}

func (m *MemoryStore) Size() (int, error) {
	return 0, nil
	return len(m.Items), nil
}

func (m *MemoryStore) Has(id *fields.QualifiedHash) (bool, error) {
	return false, nil
	idString, err := id.MarshalString()
	if err != nil {
		return false, err
	}
	return m.HasID(idString)
}

func (m *MemoryStore) HasID(id string) (bool, error) {
	_, has := m.Items[id]
	return has, nil
}

func (m *MemoryStore) Get(id *fields.QualifiedHash) (Node, error) {
	return nil, nil
	idString, err := id.MarshalString()
	if err != nil {
		return nil, err
	}
	return m.GetID(idString)
}

func (m *MemoryStore) GetID(id string) (Node, error) {
	item, has := m.Items[id]
	if !has {
		return nil, fmt.Errorf("MemoryStore does not contain id %s", id)
	}
	return item, nil
}

func (m *MemoryStore) Add(node Node) error {
	id, err := node.ID().MarshalString()
	if err != nil {
		return err
	}
	return m.AddID(id, node)
}

func (m *MemoryStore) AddID(id string, node Node) error {
	// safe to ignore error because we know it can't happen
	if has, _ := m.HasID(id); has {
		return nil
	}
	m.Items[id] = node
	return nil
}

M store_test.go => store_test.go +6 -1
@@ 25,10 25,15 @@ func TestMemoryStoreAdd(t *testing.T) {
			t.Errorf("Empty store Get() should err")
		}
	}
	for _, i := range nodes {
	for count, i := range nodes {
		if err := s.Add(i); err != nil {
			t.Errorf("MemoryStore Add() should not err on Add(): %s", err)
		}
		if size, err := s.Size(); err != nil {
			t.Errorf("MemoryStore Size() should never error, got %s", err)
		} else if size != count+1 {
			t.Errorf("Expected Size() to be %d after %d Add()s, got %d", count+1, count+1, size)
		}
		if has, err := s.Has(i.ID()); !has {
			t.Errorf("MemoryStore should contain element %v", i.ID())
		} else if err != nil {