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

import (
Jeromy's avatar
Jeromy committed
4
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
5
	"github.com/jbenet/go-ipfs/blocks/set"
6 7 8 9
	"github.com/jbenet/go-ipfs/util"
)

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

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

21
func loadIndirPin(d ds.Datastore, k ds.Key) (*indirectPin, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22 23
	var rcStore map[string]int
	err := loadSet(d, k, &rcStore)
24 25 26 27
	if err != nil {
		return nil, err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28
	refcnt := make(map[util.Key]int)
29
	var keys []util.Key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30 31
	for encK, v := range rcStore {
		k := util.B58KeyDecode(encK)
32
		keys = append(keys, k)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33
		refcnt[k] = v
34
	}
35
	log.Debugf("indirPin keys: %#v", keys)
36 37

	return &indirectPin{blockset: set.SimpleSetFromKeys(keys), refCounts: refcnt}, nil
38 39
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40 41 42 43 44 45 46 47 48
func storeIndirPin(d ds.Datastore, k ds.Key, p *indirectPin) error {

	rcStore := map[string]int{}
	for k, v := range p.refCounts {
		rcStore[util.B58KeyEncode(k)] = v
	}
	return storeSet(d, k, rcStore)
}

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
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)
}
68 69 70 71

func (i *indirectPin) Set() set.BlockSet {
	return i.blockset
}