threadunsafe.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*
  2. Open Source Initiative OSI - The MIT License (MIT):Licensing
  3. The MIT License (MIT)
  4. Copyright (c) 2013 Ralph Caraveo (deckarep@gmail.com)
  5. Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. this software and associated documentation files (the "Software"), to deal in
  7. the Software without restriction, including without limitation the rights to
  8. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  9. of the Software, and to permit persons to whom the Software is furnished to do
  10. so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in all
  12. copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. */
  21. package mapset
  22. import (
  23. "bytes"
  24. "encoding/json"
  25. "fmt"
  26. "reflect"
  27. "strings"
  28. )
  29. type threadUnsafeSet map[interface{}]struct{}
  30. // An OrderedPair represents a 2-tuple of values.
  31. type OrderedPair struct {
  32. First interface{}
  33. Second interface{}
  34. }
  35. func newThreadUnsafeSet() threadUnsafeSet {
  36. return make(threadUnsafeSet)
  37. }
  38. // Equal says whether two 2-tuples contain the same values in the same order.
  39. func (pair *OrderedPair) Equal(other OrderedPair) bool {
  40. if pair.First == other.First &&
  41. pair.Second == other.Second {
  42. return true
  43. }
  44. return false
  45. }
  46. func (set *threadUnsafeSet) Add(i interface{}) bool {
  47. _, found := (*set)[i]
  48. (*set)[i] = struct{}{}
  49. return !found //False if it existed already
  50. }
  51. func (set *threadUnsafeSet) Contains(i ...interface{}) bool {
  52. for _, val := range i {
  53. if _, ok := (*set)[val]; !ok {
  54. return false
  55. }
  56. }
  57. return true
  58. }
  59. func (set *threadUnsafeSet) IsSubset(other Set) bool {
  60. _ = other.(*threadUnsafeSet)
  61. for elem := range *set {
  62. if !other.Contains(elem) {
  63. return false
  64. }
  65. }
  66. return true
  67. }
  68. func (set *threadUnsafeSet) IsProperSubset(other Set) bool {
  69. return set.IsSubset(other) && !set.Equal(other)
  70. }
  71. func (set *threadUnsafeSet) IsSuperset(other Set) bool {
  72. return other.IsSubset(set)
  73. }
  74. func (set *threadUnsafeSet) IsProperSuperset(other Set) bool {
  75. return set.IsSuperset(other) && !set.Equal(other)
  76. }
  77. func (set *threadUnsafeSet) Union(other Set) Set {
  78. o := other.(*threadUnsafeSet)
  79. unionedSet := newThreadUnsafeSet()
  80. for elem := range *set {
  81. unionedSet.Add(elem)
  82. }
  83. for elem := range *o {
  84. unionedSet.Add(elem)
  85. }
  86. return &unionedSet
  87. }
  88. func (set *threadUnsafeSet) Intersect(other Set) Set {
  89. o := other.(*threadUnsafeSet)
  90. intersection := newThreadUnsafeSet()
  91. // loop over smaller set
  92. if set.Cardinality() < other.Cardinality() {
  93. for elem := range *set {
  94. if other.Contains(elem) {
  95. intersection.Add(elem)
  96. }
  97. }
  98. } else {
  99. for elem := range *o {
  100. if set.Contains(elem) {
  101. intersection.Add(elem)
  102. }
  103. }
  104. }
  105. return &intersection
  106. }
  107. func (set *threadUnsafeSet) Difference(other Set) Set {
  108. _ = other.(*threadUnsafeSet)
  109. difference := newThreadUnsafeSet()
  110. for elem := range *set {
  111. if !other.Contains(elem) {
  112. difference.Add(elem)
  113. }
  114. }
  115. return &difference
  116. }
  117. func (set *threadUnsafeSet) SymmetricDifference(other Set) Set {
  118. _ = other.(*threadUnsafeSet)
  119. aDiff := set.Difference(other)
  120. bDiff := other.Difference(set)
  121. return aDiff.Union(bDiff)
  122. }
  123. func (set *threadUnsafeSet) Clear() {
  124. *set = newThreadUnsafeSet()
  125. }
  126. func (set *threadUnsafeSet) Remove(i interface{}) {
  127. delete(*set, i)
  128. }
  129. func (set *threadUnsafeSet) Cardinality() int {
  130. return len(*set)
  131. }
  132. func (set *threadUnsafeSet) Each(cb func(interface{}) bool) {
  133. for elem := range *set {
  134. if cb(elem) {
  135. break
  136. }
  137. }
  138. }
  139. func (set *threadUnsafeSet) Iter() <-chan interface{} {
  140. ch := make(chan interface{})
  141. go func() {
  142. for elem := range *set {
  143. ch <- elem
  144. }
  145. close(ch)
  146. }()
  147. return ch
  148. }
  149. func (set *threadUnsafeSet) Iterator() *Iterator {
  150. iterator, ch, stopCh := newIterator()
  151. go func() {
  152. L:
  153. for elem := range *set {
  154. select {
  155. case <-stopCh:
  156. break L
  157. case ch <- elem:
  158. }
  159. }
  160. close(ch)
  161. }()
  162. return iterator
  163. }
  164. func (set *threadUnsafeSet) Equal(other Set) bool {
  165. _ = other.(*threadUnsafeSet)
  166. if set.Cardinality() != other.Cardinality() {
  167. return false
  168. }
  169. for elem := range *set {
  170. if !other.Contains(elem) {
  171. return false
  172. }
  173. }
  174. return true
  175. }
  176. func (set *threadUnsafeSet) Clone() Set {
  177. clonedSet := newThreadUnsafeSet()
  178. for elem := range *set {
  179. clonedSet.Add(elem)
  180. }
  181. return &clonedSet
  182. }
  183. func (set *threadUnsafeSet) String() string {
  184. items := make([]string, 0, len(*set))
  185. for elem := range *set {
  186. items = append(items, fmt.Sprintf("%v", elem))
  187. }
  188. return fmt.Sprintf("Set{%s}", strings.Join(items, ", "))
  189. }
  190. // String outputs a 2-tuple in the form "(A, B)".
  191. func (pair OrderedPair) String() string {
  192. return fmt.Sprintf("(%v, %v)", pair.First, pair.Second)
  193. }
  194. func (set *threadUnsafeSet) PowerSet() Set {
  195. powSet := NewThreadUnsafeSet()
  196. nullset := newThreadUnsafeSet()
  197. powSet.Add(&nullset)
  198. for es := range *set {
  199. u := newThreadUnsafeSet()
  200. j := powSet.Iter()
  201. for er := range j {
  202. p := newThreadUnsafeSet()
  203. if reflect.TypeOf(er).Name() == "" {
  204. k := er.(*threadUnsafeSet)
  205. for ek := range *(k) {
  206. p.Add(ek)
  207. }
  208. } else {
  209. p.Add(er)
  210. }
  211. p.Add(es)
  212. u.Add(&p)
  213. }
  214. powSet = powSet.Union(&u)
  215. }
  216. return powSet
  217. }
  218. func (set *threadUnsafeSet) CartesianProduct(other Set) Set {
  219. o := other.(*threadUnsafeSet)
  220. cartProduct := NewThreadUnsafeSet()
  221. for i := range *set {
  222. for j := range *o {
  223. elem := OrderedPair{First: i, Second: j}
  224. cartProduct.Add(elem)
  225. }
  226. }
  227. return cartProduct
  228. }
  229. func (set *threadUnsafeSet) ToSlice() []interface{} {
  230. keys := make([]interface{}, 0, set.Cardinality())
  231. for elem := range *set {
  232. keys = append(keys, elem)
  233. }
  234. return keys
  235. }
  236. // MarshalJSON creates a JSON array from the set, it marshals all elements
  237. func (set *threadUnsafeSet) MarshalJSON() ([]byte, error) {
  238. items := make([]string, 0, set.Cardinality())
  239. for elem := range *set {
  240. b, err := json.Marshal(elem)
  241. if err != nil {
  242. return nil, err
  243. }
  244. items = append(items, string(b))
  245. }
  246. return []byte(fmt.Sprintf("[%s]", strings.Join(items, ","))), nil
  247. }
  248. // UnmarshalJSON recreates a set from a JSON array, it only decodes
  249. // primitive types. Numbers are decoded as json.Number.
  250. func (set *threadUnsafeSet) UnmarshalJSON(b []byte) error {
  251. var i []interface{}
  252. d := json.NewDecoder(bytes.NewReader(b))
  253. d.UseNumber()
  254. err := d.Decode(&i)
  255. if err != nil {
  256. return err
  257. }
  258. for _, v := range i {
  259. switch t := v.(type) {
  260. case []interface{}, map[string]interface{}:
  261. continue
  262. default:
  263. set.Add(t)
  264. }
  265. }
  266. return nil
  267. }