github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/keyset/keyset_basic.go (about) 1 // Copyright 2020 Insolar Network Ltd. 2 // All rights reserved. 3 // This material is licensed under the Insolar License version 1.0, 4 // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md. 5 6 package keyset 7 8 func newBasicKeySet(n int) basicKeySet { 9 switch { 10 case n < 0: 11 panic("illegal value") 12 case n > 4: 13 return make(basicKeySet, n) 14 default: 15 return make(basicKeySet) 16 } 17 } 18 19 var emptyBasicKeySet = (basicKeySet)(nil) 20 21 type basicKeySet map[Key]struct{} 22 23 func (v basicKeySet) EnumKeys(fn func(k Key) bool) bool { 24 for k := range v { 25 if fn(k) { 26 return true 27 } 28 } 29 return false 30 } 31 32 func (v basicKeySet) enumRawKeys(exclusive bool, fn func(k Key, exclusive bool) bool) bool { 33 for k := range v { 34 if fn(k, exclusive) { 35 return true 36 } 37 } 38 return false 39 } 40 41 func (v basicKeySet) Count() int { 42 return len(v) 43 } 44 45 func (v basicKeySet) RawKeyCount() int { 46 return len(v) 47 } 48 49 func (v basicKeySet) isEmpty() bool { 50 return len(v) == 0 51 } 52 53 func (v basicKeySet) Contains(k Key) bool { 54 _, ok := v[k] 55 return ok 56 } 57 58 func (v basicKeySet) remove(k Key) { 59 delete(v, k) 60 } 61 62 func (v basicKeySet) add(k Key) { 63 v[k] = struct{}{} 64 } 65 66 func keyUnion(v internalKeySet, ks KeySet) basicKeySet { 67 r := v.copy(ks.RawKeyCount()) 68 ks.EnumRawKeys(func(k Key, _ bool) bool { 69 r.add(k) 70 return false 71 }) 72 return r 73 } 74 75 func keyIntersect(v internalKeySet, ks KeySet) basicKeySet { 76 kn := ks.RawKeyCount() 77 vn := v.Count() 78 if kn < vn { 79 r := make(basicKeySet, kn) 80 ks.EnumRawKeys(func(k Key, _ bool) bool { 81 if v.Contains(k) { 82 r[k] = struct{}{} 83 } 84 return false 85 }) 86 return r 87 } 88 89 exclusive := ks.IsOpenSet() 90 r := newBasicKeySet(vn) 91 v.EnumKeys(func(k Key) bool { 92 if ks.Contains(k) != exclusive { 93 r[k] = struct{}{} 94 } 95 return false 96 }) 97 return r 98 } 99 100 func keySubtract(v internalKeySet, ks KeySet) basicKeySet { 101 vn := v.Count() 102 switch kn := ks.RawKeyCount(); { 103 case kn < vn>>1: 104 r := v.copy(0) 105 ks.EnumRawKeys(func(k Key, _ bool) bool { 106 r.remove(k) 107 return false 108 }) 109 return r 110 default: 111 r := newBasicKeySet(vn) 112 exclusive := ks.IsOpenSet() 113 v.EnumKeys(func(k Key) bool { 114 if ks.Contains(k) == exclusive { 115 r[k] = struct{}{} 116 } 117 return false 118 }) 119 return r 120 } 121 }