threadunsafe.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*
  2. Open Source Initiative OSI - The MIT License (MIT):Licensing
  3. The MIT License (MIT)
  4. Copyright (c) 2013 - 2022 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. "strings"
  27. )
  28. type threadUnsafeSet[T comparable] map[T]struct{}
  29. // Assert concrete type:threadUnsafeSet adheres to Set interface.
  30. var _ Set[string] = (threadUnsafeSet[string])(nil)
  31. func newThreadUnsafeSet[T comparable]() threadUnsafeSet[T] {
  32. return make(threadUnsafeSet[T])
  33. }
  34. func newThreadUnsafeSetWithSize[T comparable](cardinality int) threadUnsafeSet[T] {
  35. return make(threadUnsafeSet[T], cardinality)
  36. }
  37. func (s threadUnsafeSet[T]) Add(v T) bool {
  38. prevLen := len(s)
  39. s[v] = struct{}{}
  40. return prevLen != len(s)
  41. }
  42. func (s threadUnsafeSet[T]) Append(v ...T) int {
  43. prevLen := len(s)
  44. for _, val := range v {
  45. (s)[val] = struct{}{}
  46. }
  47. return len(s) - prevLen
  48. }
  49. // private version of Add which doesn't return a value
  50. func (s threadUnsafeSet[T]) add(v T) {
  51. s[v] = struct{}{}
  52. }
  53. func (s threadUnsafeSet[T]) Cardinality() int {
  54. return len(s)
  55. }
  56. func (s threadUnsafeSet[T]) Clear() {
  57. // Constructions like this are optimised by compiler, and replaced by
  58. // mapclear() function, defined in
  59. // https://github.com/golang/go/blob/29bbca5c2c1ad41b2a9747890d183b6dd3a4ace4/src/runtime/map.go#L993)
  60. for key := range s {
  61. delete(s, key)
  62. }
  63. }
  64. func (s threadUnsafeSet[T]) Clone() Set[T] {
  65. clonedSet := newThreadUnsafeSetWithSize[T](s.Cardinality())
  66. for elem := range s {
  67. clonedSet.add(elem)
  68. }
  69. return clonedSet
  70. }
  71. func (s threadUnsafeSet[T]) Contains(v ...T) bool {
  72. for _, val := range v {
  73. if _, ok := s[val]; !ok {
  74. return false
  75. }
  76. }
  77. return true
  78. }
  79. // private version of Contains for a single element v
  80. func (s threadUnsafeSet[T]) contains(v T) (ok bool) {
  81. _, ok = s[v]
  82. return ok
  83. }
  84. func (s threadUnsafeSet[T]) Difference(other Set[T]) Set[T] {
  85. o := other.(threadUnsafeSet[T])
  86. diff := newThreadUnsafeSet[T]()
  87. for elem := range s {
  88. if !o.contains(elem) {
  89. diff.add(elem)
  90. }
  91. }
  92. return diff
  93. }
  94. func (s threadUnsafeSet[T]) Each(cb func(T) bool) {
  95. for elem := range s {
  96. if cb(elem) {
  97. break
  98. }
  99. }
  100. }
  101. func (s threadUnsafeSet[T]) Equal(other Set[T]) bool {
  102. o := other.(threadUnsafeSet[T])
  103. if s.Cardinality() != other.Cardinality() {
  104. return false
  105. }
  106. for elem := range s {
  107. if !o.contains(elem) {
  108. return false
  109. }
  110. }
  111. return true
  112. }
  113. func (s threadUnsafeSet[T]) Intersect(other Set[T]) Set[T] {
  114. o := other.(threadUnsafeSet[T])
  115. intersection := newThreadUnsafeSet[T]()
  116. // loop over smaller set
  117. if s.Cardinality() < other.Cardinality() {
  118. for elem := range s {
  119. if o.contains(elem) {
  120. intersection.add(elem)
  121. }
  122. }
  123. } else {
  124. for elem := range o {
  125. if s.contains(elem) {
  126. intersection.add(elem)
  127. }
  128. }
  129. }
  130. return intersection
  131. }
  132. func (s threadUnsafeSet[T]) IsProperSubset(other Set[T]) bool {
  133. return s.Cardinality() < other.Cardinality() && s.IsSubset(other)
  134. }
  135. func (s threadUnsafeSet[T]) IsProperSuperset(other Set[T]) bool {
  136. return s.Cardinality() > other.Cardinality() && s.IsSuperset(other)
  137. }
  138. func (s threadUnsafeSet[T]) IsSubset(other Set[T]) bool {
  139. o := other.(threadUnsafeSet[T])
  140. if s.Cardinality() > other.Cardinality() {
  141. return false
  142. }
  143. for elem := range s {
  144. if !o.contains(elem) {
  145. return false
  146. }
  147. }
  148. return true
  149. }
  150. func (s threadUnsafeSet[T]) IsSuperset(other Set[T]) bool {
  151. return other.IsSubset(s)
  152. }
  153. func (s threadUnsafeSet[T]) Iter() <-chan T {
  154. ch := make(chan T)
  155. go func() {
  156. for elem := range s {
  157. ch <- elem
  158. }
  159. close(ch)
  160. }()
  161. return ch
  162. }
  163. func (s threadUnsafeSet[T]) Iterator() *Iterator[T] {
  164. iterator, ch, stopCh := newIterator[T]()
  165. go func() {
  166. L:
  167. for elem := range s {
  168. select {
  169. case <-stopCh:
  170. break L
  171. case ch <- elem:
  172. }
  173. }
  174. close(ch)
  175. }()
  176. return iterator
  177. }
  178. // Pop returns a popped item in case set is not empty, or nil-value of T
  179. // if set is already empty
  180. func (s threadUnsafeSet[T]) Pop() (v T, ok bool) {
  181. for item := range s {
  182. delete(s, item)
  183. return item, true
  184. }
  185. return v, false
  186. }
  187. func (s threadUnsafeSet[T]) Remove(v T) {
  188. delete(s, v)
  189. }
  190. func (s threadUnsafeSet[T]) RemoveAll(i ...T) {
  191. for _, elem := range i {
  192. delete(s, elem)
  193. }
  194. }
  195. func (s threadUnsafeSet[T]) String() string {
  196. items := make([]string, 0, len(s))
  197. for elem := range s {
  198. items = append(items, fmt.Sprintf("%v", elem))
  199. }
  200. return fmt.Sprintf("Set{%s}", strings.Join(items, ", "))
  201. }
  202. func (s threadUnsafeSet[T]) SymmetricDifference(other Set[T]) Set[T] {
  203. o := other.(threadUnsafeSet[T])
  204. sd := newThreadUnsafeSet[T]()
  205. for elem := range s {
  206. if !o.contains(elem) {
  207. sd.add(elem)
  208. }
  209. }
  210. for elem := range o {
  211. if !s.contains(elem) {
  212. sd.add(elem)
  213. }
  214. }
  215. return sd
  216. }
  217. func (s threadUnsafeSet[T]) ToSlice() []T {
  218. keys := make([]T, 0, s.Cardinality())
  219. for elem := range s {
  220. keys = append(keys, elem)
  221. }
  222. return keys
  223. }
  224. func (s threadUnsafeSet[T]) Union(other Set[T]) Set[T] {
  225. o := other.(threadUnsafeSet[T])
  226. n := s.Cardinality()
  227. if o.Cardinality() > n {
  228. n = o.Cardinality()
  229. }
  230. unionedSet := make(threadUnsafeSet[T], n)
  231. for elem := range s {
  232. unionedSet.add(elem)
  233. }
  234. for elem := range o {
  235. unionedSet.add(elem)
  236. }
  237. return unionedSet
  238. }
  239. // MarshalJSON creates a JSON array from the set, it marshals all elements
  240. func (s threadUnsafeSet[T]) MarshalJSON() ([]byte, error) {
  241. items := make([]string, 0, s.Cardinality())
  242. for elem := range s {
  243. b, err := json.Marshal(elem)
  244. if err != nil {
  245. return nil, err
  246. }
  247. items = append(items, string(b))
  248. }
  249. return []byte(fmt.Sprintf("[%s]", strings.Join(items, ","))), nil
  250. }
  251. // UnmarshalJSON recreates a set from a JSON array, it only decodes
  252. // primitive types. Numbers are decoded as json.Number.
  253. func (s threadUnsafeSet[T]) UnmarshalJSON(b []byte) error {
  254. var i []any
  255. d := json.NewDecoder(bytes.NewReader(b))
  256. d.UseNumber()
  257. err := d.Decode(&i)
  258. if err != nil {
  259. return err
  260. }
  261. for _, v := range i {
  262. switch t := v.(type) {
  263. case T:
  264. s.add(t)
  265. default:
  266. // anything else must be skipped.
  267. continue
  268. }
  269. }
  270. return nil
  271. }