github.com/advanderveer/restic@v0.8.1-0.20171209104529-42a8c19aaea6/internal/restic/blob_set.go (about) 1 package restic 2 3 import "sort" 4 5 // BlobSet is a set of blobs. 6 type BlobSet map[BlobHandle]struct{} 7 8 // NewBlobSet returns a new BlobSet, populated with ids. 9 func NewBlobSet(handles ...BlobHandle) BlobSet { 10 m := make(BlobSet) 11 for _, h := range handles { 12 m[h] = struct{}{} 13 } 14 15 return m 16 } 17 18 // Has returns true iff id is contained in the set. 19 func (s BlobSet) Has(h BlobHandle) bool { 20 _, ok := s[h] 21 return ok 22 } 23 24 // Insert adds id to the set. 25 func (s BlobSet) Insert(h BlobHandle) { 26 s[h] = struct{}{} 27 } 28 29 // Delete removes id from the set. 30 func (s BlobSet) Delete(h BlobHandle) { 31 delete(s, h) 32 } 33 34 // Equals returns true iff s equals other. 35 func (s BlobSet) Equals(other BlobSet) bool { 36 if len(s) != len(other) { 37 return false 38 } 39 40 for h := range s { 41 if _, ok := other[h]; !ok { 42 return false 43 } 44 } 45 46 return true 47 } 48 49 // Merge adds the blobs in other to the current set. 50 func (s BlobSet) Merge(other BlobSet) { 51 for h := range other { 52 s.Insert(h) 53 } 54 } 55 56 // Intersect returns a new set containing the handles that are present in both sets. 57 func (s BlobSet) Intersect(other BlobSet) (result BlobSet) { 58 result = NewBlobSet() 59 60 set1 := s 61 set2 := other 62 63 // iterate over the smaller set 64 if len(set2) < len(set1) { 65 set1, set2 = set2, set1 66 } 67 68 for h := range set1 { 69 if set2.Has(h) { 70 result.Insert(h) 71 } 72 } 73 74 return result 75 } 76 77 // Sub returns a new set containing all handles that are present in s but not in 78 // other. 79 func (s BlobSet) Sub(other BlobSet) (result BlobSet) { 80 result = NewBlobSet() 81 for h := range s { 82 if !other.Has(h) { 83 result.Insert(h) 84 } 85 } 86 87 return result 88 } 89 90 // List returns a sorted slice of all BlobHandle in the set. 91 func (s BlobSet) List() BlobHandles { 92 list := make(BlobHandles, 0, len(s)) 93 for h := range s { 94 list = append(list, h) 95 } 96 97 sort.Sort(list) 98 99 return list 100 } 101 102 func (s BlobSet) String() string { 103 str := s.List().String() 104 if len(str) < 2 { 105 return "{}" 106 } 107 108 return "{" + str[1:len(str)-1] + "}" 109 }