datastore.go 1.28 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5
package lru

import (
	"errors"

Brian Tiger Chow's avatar
Brian Tiger Chow committed
6
	lru "github.com/jbenet/datastore.go/Godeps/_workspace/src/github.com/hashicorp/golang-lru"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
	ds "github.com/jbenet/datastore.go"
)

// Datastore uses golang-lru for internal storage.
type Datastore struct {
	cache *lru.Cache
}

// NewDatastore constructs a new LRU Datastore with given capacity.
func NewDatastore(capacity int) (*Datastore, error) {
	cache, err := lru.New(capacity)
	if err != nil {
		return nil, err
	}

	return &Datastore{cache: cache}, nil
}

// Put stores the object `value` named by `key`.
func (d *Datastore) Put(key ds.Key, value interface{}) (err error) {
	d.cache.Add(key, value)
	return nil
}

// Get retrieves the object `value` named by `key`.
func (d *Datastore) Get(key ds.Key) (value interface{}, err error) {
	val, ok := d.cache.Get(key)
	if !ok {
		return nil, ds.ErrNotFound
	}
	return val, nil
}

// Has returns whether the `key` is mapped to a `value`.
func (d *Datastore) Has(key ds.Key) (exists bool, err error) {
	return ds.GetBackedHas(d, key)
}

// Delete removes the value for given `key`.
func (d *Datastore) Delete(key ds.Key) (err error) {
	d.cache.Remove(key)
	return nil
}

// KeyList returns a list of keys in the datastore
func (d *Datastore) KeyList() ([]ds.Key, error) {
	return nil, errors.New("KeyList not implemented.")
}