indirect.go 1.2 KB
Newer Older
1 2 3
package pin

import (
4 5
	"errors"

6
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"
7
	"github.com/jbenet/go-ipfs/blocks/set"
8 9 10 11
	"github.com/jbenet/go-ipfs/util"
)

type indirectPin struct {
12
	blockset  set.BlockSet
13 14 15
	refCounts map[util.Key]int
}

16 17 18 19 20
func NewIndirectPin(dstore ds.Datastore) *indirectPin {
	return &indirectPin{
		blockset:  set.NewDBWrapperSet(dstore, set.NewSimpleBlockSet()),
		refCounts: make(map[util.Key]int),
	}
21 22
}

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
func loadIndirPin(d ds.Datastore, k ds.Key) (*indirectPin, error) {
	irefcnt, err := d.Get(k)
	if err != nil {
		return nil, err
	}
	refcnt, ok := irefcnt.(map[util.Key]int)
	if !ok {
		return nil, errors.New("invalid type from datastore")
	}

	var keys []util.Key
	for k, _ := range refcnt {
		keys = append(keys, k)
	}

	return &indirectPin{blockset: set.SimpleSetFromKeys(keys), refCounts: refcnt}, nil
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
}

func (i *indirectPin) Increment(k util.Key) {
	c := i.refCounts[k]
	i.refCounts[k] = c + 1
	if c <= 0 {
		i.blockset.AddBlock(k)
	}
}

func (i *indirectPin) Decrement(k util.Key) {
	c := i.refCounts[k] - 1
	i.refCounts[k] = c
	if c <= 0 {
		i.blockset.RemoveBlock(k)
	}
}

func (i *indirectPin) HasKey(k util.Key) bool {
	return i.blockset.HasKey(k)
}