set.go 1.3 KB
Newer Older
1 2
package cid

3 4
// Set is a implementation of a set of Cids, that is, a structure
// to which holds a single copy of every Cids that is added to it.
5 6 7 8
type Set struct {
	set map[string]struct{}
}

9
// NewSet initializes and returns a new Set.
10 11 12 13
func NewSet() *Set {
	return &Set{set: make(map[string]struct{})}
}

14
// Add puts a Cid in the Set.
15
func (s *Set) Add(c Cid) {
16 17 18
	s.set[string(c.Bytes())] = struct{}{}
}

19
// Has returns if the Set contains a given Cid.
20
func (s *Set) Has(c Cid) bool {
21 22 23 24
	_, ok := s.set[string(c.Bytes())]
	return ok
}

25
// Remove deletes a Cid from the Set.
26
func (s *Set) Remove(c Cid) {
27 28 29
	delete(s.set, string(c.Bytes()))
}

30
// Len returns how many elements the Set has.
31 32 33 34
func (s *Set) Len() int {
	return len(s.set)
}

35
// Keys returns the Cids in the set.
36 37
func (s *Set) Keys() []Cid {
	out := make([]Cid, 0, len(s.set))
38
	for k := range s.set {
39 40 41 42 43
		c, _ := Cast([]byte(k))
		out = append(out, c)
	}
	return out
}
44

45 46
// Visit adds a Cid to the set only if it is
// not in it already.
47
func (s *Set) Visit(c Cid) bool {
48 49 50 51 52 53 54
	if !s.Has(c) {
		s.Add(c)
		return true
	}

	return false
}
55

56 57
// ForEach allows to run a custom function on each
// Cid in the set.
58
func (s *Set) ForEach(f func(c Cid) error) error {
59
	for cs := range s.set {
60 61 62 63 64 65 66 67
		c, _ := Cast([]byte(cs))
		err := f(c)
		if err != nil {
			return err
		}
	}
	return nil
}
Łukasz Magiera's avatar
Łukasz Magiera committed
68