set.go 1.19 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
type Set struct {
6
	set map[Cid]struct{}
7 8
}

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

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

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

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

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
		out = append(out, k)
40 41 42
	}
	return out
}
43

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

	return false
}
54

55 56
// ForEach allows to run a custom function on each
// Cid in the set.
57
func (s *Set) ForEach(f func(c Cid) error) error {
58
	for c := range s.set {
59 60 61 62 63 64 65
		err := f(c)
		if err != nil {
			return err
		}
	}
	return nil
}