wantlist.go 1.24 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5
package wantlist

import (
	u "github.com/jbenet/go-ipfs/util"
	"sort"
6
	"sync"
Jeromy's avatar
Jeromy committed
7 8 9
)

type Wantlist struct {
10
	lk  sync.RWMutex
Jeromy's avatar
Jeromy committed
11 12 13
	set map[u.Key]*Entry
}

14
func New() *Wantlist {
Jeromy's avatar
Jeromy committed
15 16 17 18 19 20 21 22 23 24 25
	return &Wantlist{
		set: make(map[u.Key]*Entry),
	}
}

type Entry struct {
	Value    u.Key
	Priority int
}

func (w *Wantlist) Add(k u.Key, priority int) {
26 27
	w.lk.Lock()
	defer w.lk.Unlock()
Jeromy's avatar
Jeromy committed
28 29 30 31 32 33 34 35 36 37
	if _, ok := w.set[k]; ok {
		return
	}
	w.set[k] = &Entry{
		Value:    k,
		Priority: priority,
	}
}

func (w *Wantlist) Remove(k u.Key) {
38 39
	w.lk.Lock()
	defer w.lk.Unlock()
Jeromy's avatar
Jeromy committed
40 41 42 43
	delete(w.set, k)
}

func (w *Wantlist) Contains(k u.Key) bool {
44 45
	w.lk.RLock()
	defer w.lk.RUnlock()
Jeromy's avatar
Jeromy committed
46 47 48 49 50 51 52 53
	_, ok := w.set[k]
	return ok
}

type entrySlice []*Entry

func (es entrySlice) Len() int           { return len(es) }
func (es entrySlice) Swap(i, j int)      { es[i], es[j] = es[j], es[i] }
54
func (es entrySlice) Less(i, j int) bool { return es[i].Priority > es[j].Priority }
Jeromy's avatar
Jeromy committed
55 56

func (w *Wantlist) Entries() []*Entry {
57 58
	w.lk.RLock()
	defer w.lk.RUnlock()
Jeromy's avatar
Jeromy committed
59 60 61 62 63 64 65 66 67 68 69 70 71

	var es entrySlice

	for _, e := range w.set {
		es = append(es, e)
	}
	sort.Sort(es)
	return es
}

func (w *Wantlist) SortedEntries() []*Entry {
	w.lk.RLock()
	defer w.lk.RUnlock()
Jeromy's avatar
Jeromy committed
72 73 74 75 76 77 78 79
	var es entrySlice

	for _, e := range w.set {
		es = append(es, e)
	}
	sort.Sort(es)
	return es
}