bitset.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. /*
  2. Package bitset implements bitsets, a mapping
  3. between non-negative integers and boolean values. It should be more
  4. efficient than map[uint] bool.
  5. It provides methods for setting, clearing, flipping, and testing
  6. individual integers.
  7. But it also provides set intersection, union, difference,
  8. complement, and symmetric operations, as well as tests to
  9. check whether any, all, or no bits are set, and querying a
  10. bitset's current length and number of positive bits.
  11. BitSets are expanded to the size of the largest set bit; the
  12. memory allocation is approximately Max bits, where Max is
  13. the largest set bit. BitSets are never shrunk. On creation,
  14. a hint can be given for the number of bits that will be used.
  15. Many of the methods, including Set,Clear, and Flip, return
  16. a BitSet pointer, which allows for chaining.
  17. Example use:
  18. import "bitset"
  19. var b BitSet
  20. b.Set(10).Set(11)
  21. if b.Test(1000) {
  22. b.Clear(1000)
  23. }
  24. if B.Intersection(bitset.New(100).Set(10)).Count() > 1 {
  25. fmt.Println("Intersection works.")
  26. }
  27. As an alternative to BitSets, one should check out the 'big' package,
  28. which provides a (less set-theoretical) view of bitsets.
  29. */
  30. package bitset
  31. import (
  32. "bufio"
  33. "bytes"
  34. "encoding/base64"
  35. "encoding/binary"
  36. "encoding/json"
  37. "errors"
  38. "fmt"
  39. "io"
  40. "strconv"
  41. )
  42. // the wordSize of a bit set
  43. const wordSize = uint(64)
  44. // log2WordSize is lg(wordSize)
  45. const log2WordSize = uint(6)
  46. // allBits has every bit set
  47. const allBits uint64 = 0xffffffffffffffff
  48. // default binary BigEndian
  49. var binaryOrder binary.ByteOrder = binary.BigEndian
  50. // default json encoding base64.URLEncoding
  51. var base64Encoding = base64.URLEncoding
  52. // Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding)
  53. func Base64StdEncoding() { base64Encoding = base64.StdEncoding }
  54. // LittleEndian Marshal/Unmarshal Binary as Little Endian(Default: binary.BigEndian)
  55. func LittleEndian() { binaryOrder = binary.LittleEndian }
  56. // A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0.
  57. type BitSet struct {
  58. length uint
  59. set []uint64
  60. }
  61. // Error is used to distinguish errors (panics) generated in this package.
  62. type Error string
  63. // safeSet will fixup b.set to be non-nil and return the field value
  64. func (b *BitSet) safeSet() []uint64 {
  65. if b.set == nil {
  66. b.set = make([]uint64, wordsNeeded(0))
  67. }
  68. return b.set
  69. }
  70. // From is a constructor used to create a BitSet from an array of integers
  71. func From(buf []uint64) *BitSet {
  72. return FromWithLength(uint(len(buf))*64, buf)
  73. }
  74. // FromWithLength constructs from an array of integers and length.
  75. func FromWithLength(len uint, set []uint64) *BitSet {
  76. return &BitSet{len, set}
  77. }
  78. // Bytes returns the bitset as array of integers
  79. func (b *BitSet) Bytes() []uint64 {
  80. return b.set
  81. }
  82. // wordsNeeded calculates the number of words needed for i bits
  83. func wordsNeeded(i uint) int {
  84. if i > (Cap() - wordSize + 1) {
  85. return int(Cap() >> log2WordSize)
  86. }
  87. return int((i + (wordSize - 1)) >> log2WordSize)
  88. }
  89. // New creates a new BitSet with a hint that length bits will be required
  90. func New(length uint) (bset *BitSet) {
  91. defer func() {
  92. if r := recover(); r != nil {
  93. bset = &BitSet{
  94. 0,
  95. make([]uint64, 0),
  96. }
  97. }
  98. }()
  99. bset = &BitSet{
  100. length,
  101. make([]uint64, wordsNeeded(length)),
  102. }
  103. return bset
  104. }
  105. // Cap returns the total possible capacity, or number of bits
  106. func Cap() uint {
  107. return ^uint(0)
  108. }
  109. // Len returns the number of bits in the BitSet.
  110. // Note the difference to method Count, see example.
  111. func (b *BitSet) Len() uint {
  112. return b.length
  113. }
  114. // extendSetMaybe adds additional words to incorporate new bits if needed
  115. func (b *BitSet) extendSetMaybe(i uint) {
  116. if i >= b.length { // if we need more bits, make 'em
  117. if i >= Cap() {
  118. panic("You are exceeding the capacity")
  119. }
  120. nsize := wordsNeeded(i + 1)
  121. if b.set == nil {
  122. b.set = make([]uint64, nsize)
  123. } else if cap(b.set) >= nsize {
  124. b.set = b.set[:nsize] // fast resize
  125. } else if len(b.set) < nsize {
  126. newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x
  127. copy(newset, b.set)
  128. b.set = newset
  129. }
  130. b.length = i + 1
  131. }
  132. }
  133. // Test whether bit i is set.
  134. func (b *BitSet) Test(i uint) bool {
  135. if i >= b.length {
  136. return false
  137. }
  138. return b.set[i>>log2WordSize]&(1<<(i&(wordSize-1))) != 0
  139. }
  140. // Set bit i to 1, the capacity of the bitset is automatically
  141. // increased accordingly.
  142. // If i>= Cap(), this function will panic.
  143. // Warning: using a very large value for 'i'
  144. // may lead to a memory shortage and a panic: the caller is responsible
  145. // for providing sensible parameters in line with their memory capacity.
  146. func (b *BitSet) Set(i uint) *BitSet {
  147. b.extendSetMaybe(i)
  148. b.set[i>>log2WordSize] |= 1 << (i & (wordSize - 1))
  149. return b
  150. }
  151. // Clear bit i to 0
  152. func (b *BitSet) Clear(i uint) *BitSet {
  153. if i >= b.length {
  154. return b
  155. }
  156. b.set[i>>log2WordSize] &^= 1 << (i & (wordSize - 1))
  157. return b
  158. }
  159. // SetTo sets bit i to value.
  160. // If i>= Cap(), this function will panic.
  161. // Warning: using a very large value for 'i'
  162. // may lead to a memory shortage and a panic: the caller is responsible
  163. // for providing sensible parameters in line with their memory capacity.
  164. func (b *BitSet) SetTo(i uint, value bool) *BitSet {
  165. if value {
  166. return b.Set(i)
  167. }
  168. return b.Clear(i)
  169. }
  170. // Flip bit at i.
  171. // If i>= Cap(), this function will panic.
  172. // Warning: using a very large value for 'i'
  173. // may lead to a memory shortage and a panic: the caller is responsible
  174. // for providing sensible parameters in line with their memory capacity.
  175. func (b *BitSet) Flip(i uint) *BitSet {
  176. if i >= b.length {
  177. return b.Set(i)
  178. }
  179. b.set[i>>log2WordSize] ^= 1 << (i & (wordSize - 1))
  180. return b
  181. }
  182. // FlipRange bit in [start, end).
  183. // If end>= Cap(), this function will panic.
  184. // Warning: using a very large value for 'end'
  185. // may lead to a memory shortage and a panic: the caller is responsible
  186. // for providing sensible parameters in line with their memory capacity.
  187. func (b *BitSet) FlipRange(start, end uint) *BitSet {
  188. if start >= end {
  189. return b
  190. }
  191. b.extendSetMaybe(end - 1)
  192. var startWord uint = start >> log2WordSize
  193. var endWord uint = end >> log2WordSize
  194. b.set[startWord] ^= ^(^uint64(0) << (start & (wordSize - 1)))
  195. for i := startWord; i < endWord; i++ {
  196. b.set[i] = ^b.set[i]
  197. }
  198. if end & (wordSize - 1) != 0 {
  199. b.set[endWord] ^= ^uint64(0) >> (-end & (wordSize - 1))
  200. }
  201. return b
  202. }
  203. // Shrink shrinks BitSet so that the provided value is the last possible
  204. // set value. It clears all bits > the provided index and reduces the size
  205. // and length of the set.
  206. //
  207. // Note that the parameter value is not the new length in bits: it is the
  208. // maximal value that can be stored in the bitset after the function call.
  209. // The new length in bits is the parameter value + 1. Thus it is not possible
  210. // to use this function to set the length to 0, the minimal value of the length
  211. // after this function call is 1.
  212. //
  213. // A new slice is allocated to store the new bits, so you may see an increase in
  214. // memory usage until the GC runs. Normally this should not be a problem, but if you
  215. // have an extremely large BitSet its important to understand that the old BitSet will
  216. // remain in memory until the GC frees it.
  217. func (b *BitSet) Shrink(lastbitindex uint) *BitSet {
  218. length := lastbitindex + 1
  219. idx := wordsNeeded(length)
  220. if idx > len(b.set) {
  221. return b
  222. }
  223. shrunk := make([]uint64, idx)
  224. copy(shrunk, b.set[:idx])
  225. b.set = shrunk
  226. b.length = length
  227. if length < 64 {
  228. b.set[idx-1] &= (allBits >> (uint64(64) - uint64(length&(wordSize-1))))
  229. }
  230. return b
  231. }
  232. // Compact shrinks BitSet to so that we preserve all set bits, while minimizing
  233. // memory usage. Compact calls Shrink.
  234. func (b *BitSet) Compact() *BitSet {
  235. idx := len(b.set) - 1
  236. for ; idx >= 0 && b.set[idx] == 0; idx-- {
  237. }
  238. newlength := uint((idx + 1) << log2WordSize)
  239. if newlength >= b.length {
  240. return b // nothing to do
  241. }
  242. if newlength > 0 {
  243. return b.Shrink(newlength - 1)
  244. }
  245. // We preserve one word
  246. return b.Shrink(63)
  247. }
  248. // InsertAt takes an index which indicates where a bit should be
  249. // inserted. Then it shifts all the bits in the set to the left by 1, starting
  250. // from the given index position, and sets the index position to 0.
  251. //
  252. // Depending on the size of your BitSet, and where you are inserting the new entry,
  253. // this method could be extremely slow and in some cases might cause the entire BitSet
  254. // to be recopied.
  255. func (b *BitSet) InsertAt(idx uint) *BitSet {
  256. insertAtElement := (idx >> log2WordSize)
  257. // if length of set is a multiple of wordSize we need to allocate more space first
  258. if b.isLenExactMultiple() {
  259. b.set = append(b.set, uint64(0))
  260. }
  261. var i uint
  262. for i = uint(len(b.set) - 1); i > insertAtElement; i-- {
  263. // all elements above the position where we want to insert can simply by shifted
  264. b.set[i] <<= 1
  265. // we take the most significant bit of the previous element and set it as
  266. // the least significant bit of the current element
  267. b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63
  268. }
  269. // generate a mask to extract the data that we need to shift left
  270. // within the element where we insert a bit
  271. dataMask := ^(uint64(1)<<uint64(idx&(wordSize-1)) - 1)
  272. // extract that data that we'll shift
  273. data := b.set[i] & dataMask
  274. // set the positions of the data mask to 0 in the element where we insert
  275. b.set[i] &= ^dataMask
  276. // shift data mask to the left and insert its data to the slice element
  277. b.set[i] |= data << 1
  278. // add 1 to length of BitSet
  279. b.length++
  280. return b
  281. }
  282. // String creates a string representation of the Bitmap
  283. func (b *BitSet) String() string {
  284. // follows code from https://github.com/RoaringBitmap/roaring
  285. var buffer bytes.Buffer
  286. start := []byte("{")
  287. buffer.Write(start)
  288. counter := 0
  289. i, e := b.NextSet(0)
  290. for e {
  291. counter = counter + 1
  292. // to avoid exhausting the memory
  293. if counter > 0x40000 {
  294. buffer.WriteString("...")
  295. break
  296. }
  297. buffer.WriteString(strconv.FormatInt(int64(i), 10))
  298. i, e = b.NextSet(i + 1)
  299. if e {
  300. buffer.WriteString(",")
  301. }
  302. }
  303. buffer.WriteString("}")
  304. return buffer.String()
  305. }
  306. // DeleteAt deletes the bit at the given index position from
  307. // within the bitset
  308. // All the bits residing on the left of the deleted bit get
  309. // shifted right by 1
  310. // The running time of this operation may potentially be
  311. // relatively slow, O(length)
  312. func (b *BitSet) DeleteAt(i uint) *BitSet {
  313. // the index of the slice element where we'll delete a bit
  314. deleteAtElement := i >> log2WordSize
  315. // generate a mask for the data that needs to be shifted right
  316. // within that slice element that gets modified
  317. dataMask := ^((uint64(1) << (i & (wordSize - 1))) - 1)
  318. // extract the data that we'll shift right from the slice element
  319. data := b.set[deleteAtElement] & dataMask
  320. // set the masked area to 0 while leaving the rest as it is
  321. b.set[deleteAtElement] &= ^dataMask
  322. // shift the previously extracted data to the right and then
  323. // set it in the previously masked area
  324. b.set[deleteAtElement] |= (data >> 1) & dataMask
  325. // loop over all the consecutive slice elements to copy each
  326. // lowest bit into the highest position of the previous element,
  327. // then shift the entire content to the right by 1
  328. for i := int(deleteAtElement) + 1; i < len(b.set); i++ {
  329. b.set[i-1] |= (b.set[i] & 1) << 63
  330. b.set[i] >>= 1
  331. }
  332. b.length = b.length - 1
  333. return b
  334. }
  335. // NextSet returns the next bit set from the specified index,
  336. // including possibly the current index
  337. // along with an error code (true = valid, false = no set bit found)
  338. // for i,e := v.NextSet(0); e; i,e = v.NextSet(i + 1) {...}
  339. //
  340. // Users concerned with performance may want to use NextSetMany to
  341. // retrieve several values at once.
  342. func (b *BitSet) NextSet(i uint) (uint, bool) {
  343. x := int(i >> log2WordSize)
  344. if x >= len(b.set) {
  345. return 0, false
  346. }
  347. w := b.set[x]
  348. w = w >> (i & (wordSize - 1))
  349. if w != 0 {
  350. return i + trailingZeroes64(w), true
  351. }
  352. x = x + 1
  353. for x < len(b.set) {
  354. if b.set[x] != 0 {
  355. return uint(x)*wordSize + trailingZeroes64(b.set[x]), true
  356. }
  357. x = x + 1
  358. }
  359. return 0, false
  360. }
  361. // NextSetMany returns many next bit sets from the specified index,
  362. // including possibly the current index and up to cap(buffer).
  363. // If the returned slice has len zero, then no more set bits were found
  364. //
  365. // buffer := make([]uint, 256) // this should be reused
  366. // j := uint(0)
  367. // j, buffer = bitmap.NextSetMany(j, buffer)
  368. // for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j,buffer) {
  369. // for k := range buffer {
  370. // do something with buffer[k]
  371. // }
  372. // j += 1
  373. // }
  374. //
  375. //
  376. // It is possible to retrieve all set bits as follow:
  377. //
  378. // indices := make([]uint, bitmap.Count())
  379. // bitmap.NextSetMany(0, indices)
  380. //
  381. // However if bitmap.Count() is large, it might be preferable to
  382. // use several calls to NextSetMany, for performance reasons.
  383. func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) {
  384. myanswer := buffer
  385. capacity := cap(buffer)
  386. x := int(i >> log2WordSize)
  387. if x >= len(b.set) || capacity == 0 {
  388. return 0, myanswer[:0]
  389. }
  390. skip := i & (wordSize - 1)
  391. word := b.set[x] >> skip
  392. myanswer = myanswer[:capacity]
  393. size := int(0)
  394. for word != 0 {
  395. r := trailingZeroes64(word)
  396. t := word & ((^word) + 1)
  397. myanswer[size] = r + i
  398. size++
  399. if size == capacity {
  400. goto End
  401. }
  402. word = word ^ t
  403. }
  404. x++
  405. for idx, word := range b.set[x:] {
  406. for word != 0 {
  407. r := trailingZeroes64(word)
  408. t := word & ((^word) + 1)
  409. myanswer[size] = r + (uint(x+idx) << 6)
  410. size++
  411. if size == capacity {
  412. goto End
  413. }
  414. word = word ^ t
  415. }
  416. }
  417. End:
  418. if size > 0 {
  419. return myanswer[size-1], myanswer[:size]
  420. }
  421. return 0, myanswer[:0]
  422. }
  423. // NextClear returns the next clear bit from the specified index,
  424. // including possibly the current index
  425. // along with an error code (true = valid, false = no bit found i.e. all bits are set)
  426. func (b *BitSet) NextClear(i uint) (uint, bool) {
  427. x := int(i >> log2WordSize)
  428. if x >= len(b.set) {
  429. return 0, false
  430. }
  431. w := b.set[x]
  432. w = w >> (i & (wordSize - 1))
  433. wA := allBits >> (i & (wordSize - 1))
  434. index := i + trailingZeroes64(^w)
  435. if w != wA && index < b.length {
  436. return index, true
  437. }
  438. x++
  439. for x < len(b.set) {
  440. index = uint(x)*wordSize + trailingZeroes64(^b.set[x])
  441. if b.set[x] != allBits && index < b.length {
  442. return index, true
  443. }
  444. x++
  445. }
  446. return 0, false
  447. }
  448. // ClearAll clears the entire BitSet
  449. func (b *BitSet) ClearAll() *BitSet {
  450. if b != nil && b.set != nil {
  451. for i := range b.set {
  452. b.set[i] = 0
  453. }
  454. }
  455. return b
  456. }
  457. // wordCount returns the number of words used in a bit set
  458. func (b *BitSet) wordCount() int {
  459. return len(b.set)
  460. }
  461. // Clone this BitSet
  462. func (b *BitSet) Clone() *BitSet {
  463. c := New(b.length)
  464. if b.set != nil { // Clone should not modify current object
  465. copy(c.set, b.set)
  466. }
  467. return c
  468. }
  469. // Copy into a destination BitSet using the Go array copy semantics:
  470. // the number of bits copied is the minimum of the number of bits in the current
  471. // BitSet (Len()) and the destination Bitset.
  472. // We return the number of bits copied in the destination BitSet.
  473. func (b *BitSet) Copy(c *BitSet) (count uint) {
  474. if c == nil {
  475. return
  476. }
  477. if b.set != nil { // Copy should not modify current object
  478. copy(c.set, b.set)
  479. }
  480. count = c.length
  481. if b.length < c.length {
  482. count = b.length
  483. }
  484. return
  485. }
  486. // CopyFull copies into a destination BitSet such that the destination is
  487. // identical to the source after the operation, allocating memory if necessary.
  488. func (b *BitSet) CopyFull(c *BitSet) {
  489. if c == nil {
  490. return
  491. }
  492. c.length = b.length
  493. if len(b.set) == 0 {
  494. if c.set != nil {
  495. c.set = c.set[:0]
  496. }
  497. } else {
  498. if cap(c.set) < len(b.set) {
  499. c.set = make([]uint64, len(b.set))
  500. } else {
  501. c.set = c.set[:len(b.set)]
  502. }
  503. copy(c.set, b.set)
  504. }
  505. }
  506. // Count (number of set bits).
  507. // Also known as "popcount" or "population count".
  508. func (b *BitSet) Count() uint {
  509. if b != nil && b.set != nil {
  510. return uint(popcntSlice(b.set))
  511. }
  512. return 0
  513. }
  514. // Equal tests the equivalence of two BitSets.
  515. // False if they are of different sizes, otherwise true
  516. // only if all the same bits are set
  517. func (b *BitSet) Equal(c *BitSet) bool {
  518. if c == nil || b == nil {
  519. return c == b
  520. }
  521. if b.length != c.length {
  522. return false
  523. }
  524. if b.length == 0 { // if they have both length == 0, then could have nil set
  525. return true
  526. }
  527. // testing for equality shoud not transform the bitset (no call to safeSet)
  528. for p, v := range b.set {
  529. if c.set[p] != v {
  530. return false
  531. }
  532. }
  533. return true
  534. }
  535. func panicIfNull(b *BitSet) {
  536. if b == nil {
  537. panic(Error("BitSet must not be null"))
  538. }
  539. }
  540. // Difference of base set and other set
  541. // This is the BitSet equivalent of &^ (and not)
  542. func (b *BitSet) Difference(compare *BitSet) (result *BitSet) {
  543. panicIfNull(b)
  544. panicIfNull(compare)
  545. result = b.Clone() // clone b (in case b is bigger than compare)
  546. l := int(compare.wordCount())
  547. if l > int(b.wordCount()) {
  548. l = int(b.wordCount())
  549. }
  550. for i := 0; i < l; i++ {
  551. result.set[i] = b.set[i] &^ compare.set[i]
  552. }
  553. return
  554. }
  555. // DifferenceCardinality computes the cardinality of the differnce
  556. func (b *BitSet) DifferenceCardinality(compare *BitSet) uint {
  557. panicIfNull(b)
  558. panicIfNull(compare)
  559. l := int(compare.wordCount())
  560. if l > int(b.wordCount()) {
  561. l = int(b.wordCount())
  562. }
  563. cnt := uint64(0)
  564. cnt += popcntMaskSlice(b.set[:l], compare.set[:l])
  565. cnt += popcntSlice(b.set[l:])
  566. return uint(cnt)
  567. }
  568. // InPlaceDifference computes the difference of base set and other set
  569. // This is the BitSet equivalent of &^ (and not)
  570. func (b *BitSet) InPlaceDifference(compare *BitSet) {
  571. panicIfNull(b)
  572. panicIfNull(compare)
  573. l := int(compare.wordCount())
  574. if l > int(b.wordCount()) {
  575. l = int(b.wordCount())
  576. }
  577. for i := 0; i < l; i++ {
  578. b.set[i] &^= compare.set[i]
  579. }
  580. }
  581. // Convenience function: return two bitsets ordered by
  582. // increasing length. Note: neither can be nil
  583. func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) {
  584. if a.length <= b.length {
  585. ap, bp = a, b
  586. } else {
  587. ap, bp = b, a
  588. }
  589. return
  590. }
  591. // Intersection of base set and other set
  592. // This is the BitSet equivalent of & (and)
  593. func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) {
  594. panicIfNull(b)
  595. panicIfNull(compare)
  596. b, compare = sortByLength(b, compare)
  597. result = New(b.length)
  598. for i, word := range b.set {
  599. result.set[i] = word & compare.set[i]
  600. }
  601. return
  602. }
  603. // IntersectionCardinality computes the cardinality of the union
  604. func (b *BitSet) IntersectionCardinality(compare *BitSet) uint {
  605. panicIfNull(b)
  606. panicIfNull(compare)
  607. b, compare = sortByLength(b, compare)
  608. cnt := popcntAndSlice(b.set, compare.set)
  609. return uint(cnt)
  610. }
  611. // InPlaceIntersection destructively computes the intersection of
  612. // base set and the compare set.
  613. // This is the BitSet equivalent of & (and)
  614. func (b *BitSet) InPlaceIntersection(compare *BitSet) {
  615. panicIfNull(b)
  616. panicIfNull(compare)
  617. l := int(compare.wordCount())
  618. if l > int(b.wordCount()) {
  619. l = int(b.wordCount())
  620. }
  621. for i := 0; i < l; i++ {
  622. b.set[i] &= compare.set[i]
  623. }
  624. for i := l; i < len(b.set); i++ {
  625. b.set[i] = 0
  626. }
  627. if compare.length > 0 {
  628. b.extendSetMaybe(compare.length - 1)
  629. }
  630. }
  631. // Union of base set and other set
  632. // This is the BitSet equivalent of | (or)
  633. func (b *BitSet) Union(compare *BitSet) (result *BitSet) {
  634. panicIfNull(b)
  635. panicIfNull(compare)
  636. b, compare = sortByLength(b, compare)
  637. result = compare.Clone()
  638. for i, word := range b.set {
  639. result.set[i] = word | compare.set[i]
  640. }
  641. return
  642. }
  643. // UnionCardinality computes the cardinality of the uniton of the base set
  644. // and the compare set.
  645. func (b *BitSet) UnionCardinality(compare *BitSet) uint {
  646. panicIfNull(b)
  647. panicIfNull(compare)
  648. b, compare = sortByLength(b, compare)
  649. cnt := popcntOrSlice(b.set, compare.set)
  650. if len(compare.set) > len(b.set) {
  651. cnt += popcntSlice(compare.set[len(b.set):])
  652. }
  653. return uint(cnt)
  654. }
  655. // InPlaceUnion creates the destructive union of base set and compare set.
  656. // This is the BitSet equivalent of | (or).
  657. func (b *BitSet) InPlaceUnion(compare *BitSet) {
  658. panicIfNull(b)
  659. panicIfNull(compare)
  660. l := int(compare.wordCount())
  661. if l > int(b.wordCount()) {
  662. l = int(b.wordCount())
  663. }
  664. if compare.length > 0 {
  665. b.extendSetMaybe(compare.length - 1)
  666. }
  667. for i := 0; i < l; i++ {
  668. b.set[i] |= compare.set[i]
  669. }
  670. if len(compare.set) > l {
  671. for i := l; i < len(compare.set); i++ {
  672. b.set[i] = compare.set[i]
  673. }
  674. }
  675. }
  676. // SymmetricDifference of base set and other set
  677. // This is the BitSet equivalent of ^ (xor)
  678. func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) {
  679. panicIfNull(b)
  680. panicIfNull(compare)
  681. b, compare = sortByLength(b, compare)
  682. // compare is bigger, so clone it
  683. result = compare.Clone()
  684. for i, word := range b.set {
  685. result.set[i] = word ^ compare.set[i]
  686. }
  687. return
  688. }
  689. // SymmetricDifferenceCardinality computes the cardinality of the symmetric difference
  690. func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint {
  691. panicIfNull(b)
  692. panicIfNull(compare)
  693. b, compare = sortByLength(b, compare)
  694. cnt := popcntXorSlice(b.set, compare.set)
  695. if len(compare.set) > len(b.set) {
  696. cnt += popcntSlice(compare.set[len(b.set):])
  697. }
  698. return uint(cnt)
  699. }
  700. // InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set
  701. // This is the BitSet equivalent of ^ (xor)
  702. func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) {
  703. panicIfNull(b)
  704. panicIfNull(compare)
  705. l := int(compare.wordCount())
  706. if l > int(b.wordCount()) {
  707. l = int(b.wordCount())
  708. }
  709. if compare.length > 0 {
  710. b.extendSetMaybe(compare.length - 1)
  711. }
  712. for i := 0; i < l; i++ {
  713. b.set[i] ^= compare.set[i]
  714. }
  715. if len(compare.set) > l {
  716. for i := l; i < len(compare.set); i++ {
  717. b.set[i] = compare.set[i]
  718. }
  719. }
  720. }
  721. // Is the length an exact multiple of word sizes?
  722. func (b *BitSet) isLenExactMultiple() bool {
  723. return b.length%wordSize == 0
  724. }
  725. // Clean last word by setting unused bits to 0
  726. func (b *BitSet) cleanLastWord() {
  727. if !b.isLenExactMultiple() {
  728. b.set[len(b.set)-1] &= allBits >> (wordSize - b.length%wordSize)
  729. }
  730. }
  731. // Complement computes the (local) complement of a biset (up to length bits)
  732. func (b *BitSet) Complement() (result *BitSet) {
  733. panicIfNull(b)
  734. result = New(b.length)
  735. for i, word := range b.set {
  736. result.set[i] = ^word
  737. }
  738. result.cleanLastWord()
  739. return
  740. }
  741. // All returns true if all bits are set, false otherwise. Returns true for
  742. // empty sets.
  743. func (b *BitSet) All() bool {
  744. panicIfNull(b)
  745. return b.Count() == b.length
  746. }
  747. // None returns true if no bit is set, false otherwise. Returns true for
  748. // empty sets.
  749. func (b *BitSet) None() bool {
  750. panicIfNull(b)
  751. if b != nil && b.set != nil {
  752. for _, word := range b.set {
  753. if word > 0 {
  754. return false
  755. }
  756. }
  757. return true
  758. }
  759. return true
  760. }
  761. // Any returns true if any bit is set, false otherwise
  762. func (b *BitSet) Any() bool {
  763. panicIfNull(b)
  764. return !b.None()
  765. }
  766. // IsSuperSet returns true if this is a superset of the other set
  767. func (b *BitSet) IsSuperSet(other *BitSet) bool {
  768. for i, e := other.NextSet(0); e; i, e = other.NextSet(i + 1) {
  769. if !b.Test(i) {
  770. return false
  771. }
  772. }
  773. return true
  774. }
  775. // IsStrictSuperSet returns true if this is a strict superset of the other set
  776. func (b *BitSet) IsStrictSuperSet(other *BitSet) bool {
  777. return b.Count() > other.Count() && b.IsSuperSet(other)
  778. }
  779. // DumpAsBits dumps a bit set as a string of bits
  780. func (b *BitSet) DumpAsBits() string {
  781. if b.set == nil {
  782. return "."
  783. }
  784. buffer := bytes.NewBufferString("")
  785. i := len(b.set) - 1
  786. for ; i >= 0; i-- {
  787. fmt.Fprintf(buffer, "%064b.", b.set[i])
  788. }
  789. return buffer.String()
  790. }
  791. // BinaryStorageSize returns the binary storage requirements
  792. func (b *BitSet) BinaryStorageSize() int {
  793. return binary.Size(uint64(0)) + binary.Size(b.set)
  794. }
  795. // WriteTo writes a BitSet to a stream
  796. func (b *BitSet) WriteTo(stream io.Writer) (int64, error) {
  797. length := uint64(b.length)
  798. // Write length
  799. err := binary.Write(stream, binaryOrder, length)
  800. if err != nil {
  801. return 0, err
  802. }
  803. // Write set
  804. // current implementation of bufio.Writer is more memory efficient than
  805. // binary.Write for large set
  806. writer := bufio.NewWriter(stream)
  807. var item = make([]byte, binary.Size(uint64(0))) // for serializing one uint64
  808. for i := range b.set {
  809. binaryOrder.PutUint64(item, b.set[i])
  810. if nn, err := writer.Write(item); err != nil {
  811. return int64(i*binary.Size(uint64(0)) + nn), err
  812. }
  813. }
  814. err = writer.Flush()
  815. return int64(b.BinaryStorageSize()), err
  816. }
  817. // ReadFrom reads a BitSet from a stream written using WriteTo
  818. func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) {
  819. var length uint64
  820. // Read length first
  821. err := binary.Read(stream, binaryOrder, &length)
  822. if err != nil {
  823. return 0, err
  824. }
  825. newset := New(uint(length))
  826. if uint64(newset.length) != length {
  827. return 0, errors.New("unmarshalling error: type mismatch")
  828. }
  829. // Read remaining bytes as set
  830. // current implementation bufio.Reader is more memory efficient than
  831. // binary.Read for large set
  832. reader := bufio.NewReader(stream)
  833. var item = make([]byte, binary.Size(uint64(0))) // one uint64
  834. for i := uint64(0); i < length; i++ {
  835. if _, err := reader.Read(item); err != nil {
  836. if err == io.EOF {
  837. break // done
  838. }
  839. return 0, err
  840. }
  841. newset.set[i] = binaryOrder.Uint64(item)
  842. }
  843. *b = *newset
  844. return int64(b.BinaryStorageSize()), nil
  845. }
  846. // MarshalBinary encodes a BitSet into a binary form and returns the result.
  847. func (b *BitSet) MarshalBinary() ([]byte, error) {
  848. var buf bytes.Buffer
  849. _, err := b.WriteTo(&buf)
  850. if err != nil {
  851. return []byte{}, err
  852. }
  853. return buf.Bytes(), err
  854. }
  855. // UnmarshalBinary decodes the binary form generated by MarshalBinary.
  856. func (b *BitSet) UnmarshalBinary(data []byte) error {
  857. buf := bytes.NewReader(data)
  858. _, err := b.ReadFrom(buf)
  859. return err
  860. }
  861. // MarshalJSON marshals a BitSet as a JSON structure
  862. func (b *BitSet) MarshalJSON() ([]byte, error) {
  863. buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize()))
  864. _, err := b.WriteTo(buffer)
  865. if err != nil {
  866. return nil, err
  867. }
  868. // URLEncode all bytes
  869. return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes()))
  870. }
  871. // UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON
  872. func (b *BitSet) UnmarshalJSON(data []byte) error {
  873. // Unmarshal as string
  874. var s string
  875. err := json.Unmarshal(data, &s)
  876. if err != nil {
  877. return err
  878. }
  879. // URLDecode string
  880. buf, err := base64Encoding.DecodeString(s)
  881. if err != nil {
  882. return err
  883. }
  884. _, err = b.ReadFrom(bytes.NewReader(buf))
  885. return err
  886. }