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

import (
	"errors"

6
	lru "github.com/jbenet/go-datastore/Godeps/_workspace/src/github.com/hashicorp/golang-lru"
7

8
	ds "github.com/jbenet/go-datastore"
9
	dsq "github.com/jbenet/go-datastore/query"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
)

// 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
54
func (d *Datastore) Query(q dsq.Query) (dsq.Results, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55 56
	return nil, errors.New("KeyList not implemented.")
}
Jeromy's avatar
Jeromy committed
57 58 59 60 61 62 63 64

func (d *Datastore) Close() error {
	return nil
}

func (d *Datastore) Batch() (ds.Batch, error) {
	return nil, ds.ErrBatchUnsupported
}