threadunsafe.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. if found {
  49. return false //False if it existed already
  50. }
  51. (*set)[i] = struct{}{}
  52. return true
  53. }
  54. func (set *threadUnsafeSet) Contains(i ...interface{}) bool {
  55. for _, val := range i {
  56. if _, ok := (*set)[val]; !ok {
  57. return false
  58. }
  59. }
  60. return true
  61. }
  62. func (set *threadUnsafeSet) IsSubset(other Set) bool {
  63. _ = other.(*threadUnsafeSet)
  64. for elem := range *set {
  65. if !other.Contains(elem) {
  66. return false
  67. }
  68. }
  69. return true
  70. }
  71. func (set *threadUnsafeSet) IsProperSubset(other Set) bool {
  72. return set.IsSubset(other) && !set.Equal(other)
  73. }
  74. func (set *threadUnsafeSet) IsSuperset(other Set) bool {
  75. return other.IsSubset(set)
  76. }
  77. func (set *threadUnsafeSet) IsProperSuperset(other Set) bool {
  78. return set.IsSuperset(other) && !set.Equal(other)
  79. }
  80. func (set *threadUnsafeSet) Union(other Set) Set {
  81. o := other.(*threadUnsafeSet)
  82. unionedSet := newThreadUnsafeSet()
  83. for elem := range *set {
  84. unionedSet.Add(elem)
  85. }
  86. for elem := range *o {
  87. unionedSet.Add(elem)
  88. }
  89. return &unionedSet
  90. }
  91. func (set *threadUnsafeSet) Intersect(other Set) Set {
  92. o := other.(*threadUnsafeSet)
  93. intersection := newThreadUnsafeSet()
  94. // loop over smaller set
  95. if set.Cardinality() < other.Cardinality() {
  96. for elem := range *set {
  97. if other.Contains(elem) {
  98. intersection.Add(elem)
  99. }
  100. }
  101. } else {
  102. for elem := range *o {
  103. if set.Contains(elem) {
  104. intersection.Add(elem)
  105. }
  106. }
  107. }
  108. return &intersection
  109. }
  110. func (set *threadUnsafeSet) Difference(other Set) Set {
  111. _ = other.(*threadUnsafeSet)
  112. difference := newThreadUnsafeSet()
  113. for elem := range *set {
  114. if !other.Contains(elem) {
  115. difference.Add(elem)
  116. }
  117. }
  118. return &difference
  119. }
  120. func (set *threadUnsafeSet) SymmetricDifference(other Set) Set {
  121. _ = other.(*threadUnsafeSet)
  122. aDiff := set.Difference(other)
  123. bDiff := other.Difference(set)
  124. return aDiff.Union(bDiff)
  125. }
  126. func (set *threadUnsafeSet) Clear() {
  127. *set = newThreadUnsafeSet()
  128. }
  129. func (set *threadUnsafeSet) Remove(i interface{}) {
  130. delete(*set, i)
  131. }
  132. func (set *threadUnsafeSet) Cardinality() int {
  133. return len(*set)
  134. }
  135. func (set *threadUnsafeSet) Each(cb func(interface{}) bool) {
  136. for elem := range *set {
  137. if cb(elem) {
  138. break
  139. }
  140. }
  141. }
  142. func (set *threadUnsafeSet) Iter() <-chan interface{} {
  143. ch := make(chan interface{})
  144. go func() {
  145. for elem := range *set {
  146. ch <- elem
  147. }
  148. close(ch)
  149. }()
  150. return ch
  151. }
  152. func (set *threadUnsafeSet) Iterator() *Iterator {
  153. iterator, ch, stopCh := newIterator()
  154. go func() {
  155. L:
  156. for elem := range *set {
  157. select {
  158. case <-stopCh:
  159. break L
  160. case ch <- elem:
  161. }
  162. }
  163. close(ch)
  164. }()
  165. return iterator
  166. }
  167. func (set *threadUnsafeSet) Equal(other Set) bool {
  168. _ = other.(*threadUnsafeSet)
  169. if set.Cardinality() != other.Cardinality() {
  170. return false
  171. }
  172. for elem := range *set {
  173. if !other.Contains(elem) {
  174. return false
  175. }
  176. }
  177. return true
  178. }
  179. func (set *threadUnsafeSet) Clone() Set {
  180. clonedSet := newThreadUnsafeSet()
  181. for elem := range *set {
  182. clonedSet.Add(elem)
  183. }
  184. return &clonedSet
  185. }
  186. func (set *threadUnsafeSet) String() string {
  187. items := make([]string, 0, len(*set))
  188. for elem := range *set {
  189. items = append(items, fmt.Sprintf("%v", elem))
  190. }
  191. return fmt.Sprintf("Set{%s}", strings.Join(items, ", "))
  192. }
  193. // String outputs a 2-tuple in the form "(A, B)".
  194. func (pair OrderedPair) String() string {
  195. return fmt.Sprintf("(%v, %v)", pair.First, pair.Second)
  196. }
  197. func (set *threadUnsafeSet) Pop() interface{} {
  198. for item := range *set {
  199. delete(*set, item)
  200. return item
  201. }
  202. return nil
  203. }
  204. func (set *threadUnsafeSet) PowerSet() Set {
  205. powSet := NewThreadUnsafeSet()
  206. nullset := newThreadUnsafeSet()
  207. powSet.Add(&nullset)
  208. for es := range *set {
  209. u := newThreadUnsafeSet()
  210. j := powSet.Iter()
  211. for er := range j {
  212. p := newThreadUnsafeSet()
  213. if reflect.TypeOf(er).Name() == "" {
  214. k := er.(*threadUnsafeSet)
  215. for ek := range *(k) {
  216. p.Add(ek)
  217. }
  218. } else {
  219. p.Add(er)
  220. }
  221. p.Add(es)
  222. u.Add(&p)
  223. }
  224. powSet = powSet.Union(&u)
  225. }
  226. return powSet
  227. }
  228. func (set *threadUnsafeSet) CartesianProduct(other Set) Set {
  229. o := other.(*threadUnsafeSet)
  230. cartProduct := NewThreadUnsafeSet()
  231. for i := range *set {
  232. for j := range *o {
  233. elem := OrderedPair{First: i, Second: j}
  234. cartProduct.Add(elem)
  235. }
  236. }
  237. return cartProduct
  238. }
  239. func (set *threadUnsafeSet) ToSlice() []interface{} {
  240. keys := make([]interface{}, 0, set.Cardinality())
  241. for elem := range *set {
  242. keys = append(keys, elem)
  243. }
  244. return keys
  245. }
  246. // MarshalJSON creates a JSON array from the set, it marshals all elements
  247. func (set *threadUnsafeSet) MarshalJSON() ([]byte, error) {
  248. items := make([]string, 0, set.Cardinality())
  249. for elem := range *set {
  250. b, err := json.Marshal(elem)
  251. if err != nil {
  252. return nil, err
  253. }
  254. items = append(items, string(b))
  255. }
  256. return []byte(fmt.Sprintf("[%s]", strings.Join(items, ","))), nil
  257. }
  258. // UnmarshalJSON recreates a set from a JSON array, it only decodes
  259. // primitive types. Numbers are decoded as json.Number.
  260. func (set *threadUnsafeSet) UnmarshalJSON(b []byte) error {
  261. var i []interface{}
  262. d := json.NewDecoder(bytes.NewReader(b))
  263. d.UseNumber()
  264. err := d.Decode(&i)
  265. if err != nil {
  266. return err
  267. }
  268. for _, v := range i {
  269. switch t := v.(type) {
  270. case []interface{}, map[string]interface{}:
  271. continue
  272. default:
  273. set.Add(t)
  274. }
  275. }
  276. return nil
  277. }