You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bitset.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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 &BitSet{uint(len(buf)) * 64, buf}
  73. }
  74. // Bytes returns the bitset as array of integers
  75. func (b *BitSet) Bytes() []uint64 {
  76. return b.set
  77. }
  78. // wordsNeeded calculates the number of words needed for i bits
  79. func wordsNeeded(i uint) int {
  80. if i > (Cap() - wordSize + 1) {
  81. return int(Cap() >> log2WordSize)
  82. }
  83. return int((i + (wordSize - 1)) >> log2WordSize)
  84. }
  85. // New creates a new BitSet with a hint that length bits will be required
  86. func New(length uint) (bset *BitSet) {
  87. defer func() {
  88. if r := recover(); r != nil {
  89. bset = &BitSet{
  90. 0,
  91. make([]uint64, 0),
  92. }
  93. }
  94. }()
  95. bset = &BitSet{
  96. length,
  97. make([]uint64, wordsNeeded(length)),
  98. }
  99. return bset
  100. }
  101. // Cap returns the total possible capacity, or number of bits
  102. func Cap() uint {
  103. return ^uint(0)
  104. }
  105. // Len returns the length of the BitSet in words
  106. func (b *BitSet) Len() uint {
  107. return b.length
  108. }
  109. // extendSetMaybe adds additional words to incorporate new bits if needed
  110. func (b *BitSet) extendSetMaybe(i uint) {
  111. if i >= b.length { // if we need more bits, make 'em
  112. nsize := wordsNeeded(i + 1)
  113. if b.set == nil {
  114. b.set = make([]uint64, nsize)
  115. } else if cap(b.set) >= nsize {
  116. b.set = b.set[:nsize] // fast resize
  117. } else if len(b.set) < nsize {
  118. newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x
  119. copy(newset, b.set)
  120. b.set = newset
  121. }
  122. b.length = i + 1
  123. }
  124. }
  125. // Test whether bit i is set.
  126. func (b *BitSet) Test(i uint) bool {
  127. if i >= b.length {
  128. return false
  129. }
  130. return b.set[i>>log2WordSize]&(1<<(i&(wordSize-1))) != 0
  131. }
  132. // Set bit i to 1
  133. func (b *BitSet) Set(i uint) *BitSet {
  134. b.extendSetMaybe(i)
  135. b.set[i>>log2WordSize] |= 1 << (i & (wordSize - 1))
  136. return b
  137. }
  138. // Clear bit i to 0
  139. func (b *BitSet) Clear(i uint) *BitSet {
  140. if i >= b.length {
  141. return b
  142. }
  143. b.set[i>>log2WordSize] &^= 1 << (i & (wordSize - 1))
  144. return b
  145. }
  146. // SetTo sets bit i to value
  147. func (b *BitSet) SetTo(i uint, value bool) *BitSet {
  148. if value {
  149. return b.Set(i)
  150. }
  151. return b.Clear(i)
  152. }
  153. // Flip bit at i
  154. func (b *BitSet) Flip(i uint) *BitSet {
  155. if i >= b.length {
  156. return b.Set(i)
  157. }
  158. b.set[i>>log2WordSize] ^= 1 << (i & (wordSize - 1))
  159. return b
  160. }
  161. // Shrink shrinks BitSet to desired length in bits. It clears all bits > length
  162. // and reduces the size and length of the set.
  163. //
  164. // A new slice is allocated to store the new bits, so you may see an increase in
  165. // memory usage until the GC runs. Normally this should not be a problem, but if you
  166. // have an extremely large BitSet its important to understand that the old BitSet will
  167. // remain in memory until the GC frees it.
  168. func (b *BitSet) Shrink(length uint) *BitSet {
  169. idx := wordsNeeded(length + 1)
  170. if idx > len(b.set) {
  171. return b
  172. }
  173. shrunk := make([]uint64, idx)
  174. copy(shrunk, b.set[:idx])
  175. b.set = shrunk
  176. b.length = length + 1
  177. b.set[idx-1] &= (allBits >> (uint64(64) - uint64(length&(wordSize-1)) - 1))
  178. return b
  179. }
  180. // InsertAt takes an index which indicates where a bit should be
  181. // inserted. Then it shifts all the bits in the set to the left by 1, starting
  182. // from the given index position, and sets the index position to 0.
  183. //
  184. // Depending on the size of your BitSet, and where you are inserting the new entry,
  185. // this method could be extremely slow and in some cases might cause the entire BitSet
  186. // to be recopied.
  187. func (b *BitSet) InsertAt(idx uint) *BitSet {
  188. insertAtElement := (idx >> log2WordSize)
  189. // if length of set is a multiple of wordSize we need to allocate more space first
  190. if b.isLenExactMultiple() {
  191. b.set = append(b.set, uint64(0))
  192. }
  193. var i uint
  194. for i = uint(len(b.set) - 1); i > insertAtElement; i-- {
  195. // all elements above the position where we want to insert can simply by shifted
  196. b.set[i] <<= 1
  197. // we take the most significant bit of the previous element and set it as
  198. // the least significant bit of the current element
  199. b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63
  200. }
  201. // generate a mask to extract the data that we need to shift left
  202. // within the element where we insert a bit
  203. dataMask := ^(uint64(1)<<uint64(idx&(wordSize-1)) - 1)
  204. // extract that data that we'll shift
  205. data := b.set[i] & dataMask
  206. // set the positions of the data mask to 0 in the element where we insert
  207. b.set[i] &= ^dataMask
  208. // shift data mask to the left and insert its data to the slice element
  209. b.set[i] |= data << 1
  210. // add 1 to length of BitSet
  211. b.length++
  212. return b
  213. }
  214. // String creates a string representation of the Bitmap
  215. func (b *BitSet) String() string {
  216. // follows code from https://github.com/RoaringBitmap/roaring
  217. var buffer bytes.Buffer
  218. start := []byte("{")
  219. buffer.Write(start)
  220. counter := 0
  221. i, e := b.NextSet(0)
  222. for e {
  223. counter = counter + 1
  224. // to avoid exhausting the memory
  225. if counter > 0x40000 {
  226. buffer.WriteString("...")
  227. break
  228. }
  229. buffer.WriteString(strconv.FormatInt(int64(i), 10))
  230. i, e = b.NextSet(i + 1)
  231. if e {
  232. buffer.WriteString(",")
  233. }
  234. }
  235. buffer.WriteString("}")
  236. return buffer.String()
  237. }
  238. // DeleteAt deletes the bit at the given index position from
  239. // within the bitset
  240. // All the bits residing on the left of the deleted bit get
  241. // shifted right by 1
  242. // The running time of this operation may potentially be
  243. // relatively slow, O(length)
  244. func (b *BitSet) DeleteAt(i uint) *BitSet {
  245. // the index of the slice element where we'll delete a bit
  246. deleteAtElement := i >> log2WordSize
  247. // generate a mask for the data that needs to be shifted right
  248. // within that slice element that gets modified
  249. dataMask := ^((uint64(1) << (i & (wordSize - 1))) - 1)
  250. // extract the data that we'll shift right from the slice element
  251. data := b.set[deleteAtElement] & dataMask
  252. // set the masked area to 0 while leaving the rest as it is
  253. b.set[deleteAtElement] &= ^dataMask
  254. // shift the previously extracted data to the right and then
  255. // set it in the previously masked area
  256. b.set[deleteAtElement] |= (data >> 1) & dataMask
  257. // loop over all the consecutive slice elements to copy each
  258. // lowest bit into the highest position of the previous element,
  259. // then shift the entire content to the right by 1
  260. for i := int(deleteAtElement) + 1; i < len(b.set); i++ {
  261. b.set[i-1] |= (b.set[i] & 1) << 63
  262. b.set[i] >>= 1
  263. }
  264. b.length = b.length - 1
  265. return b
  266. }
  267. // NextSet returns the next bit set from the specified index,
  268. // including possibly the current index
  269. // along with an error code (true = valid, false = no set bit found)
  270. // for i,e := v.NextSet(0); e; i,e = v.NextSet(i + 1) {...}
  271. func (b *BitSet) NextSet(i uint) (uint, bool) {
  272. x := int(i >> log2WordSize)
  273. if x >= len(b.set) {
  274. return 0, false
  275. }
  276. w := b.set[x]
  277. w = w >> (i & (wordSize - 1))
  278. if w != 0 {
  279. return i + trailingZeroes64(w), true
  280. }
  281. x = x + 1
  282. for x < len(b.set) {
  283. if b.set[x] != 0 {
  284. return uint(x)*wordSize + trailingZeroes64(b.set[x]), true
  285. }
  286. x = x + 1
  287. }
  288. return 0, false
  289. }
  290. // NextSetMany returns many next bit sets from the specified index,
  291. // including possibly the current index and up to cap(buffer).
  292. // If the returned slice has len zero, then no more set bits were found
  293. //
  294. // buffer := make([]uint, 256) // this should be reused
  295. // j := uint(0)
  296. // j, buffer = bitmap.NextSetMany(j, buffer)
  297. // for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j,buffer) {
  298. // for k := range buffer {
  299. // do something with buffer[k]
  300. // }
  301. // j += 1
  302. // }
  303. //
  304. func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) {
  305. myanswer := buffer
  306. capacity := cap(buffer)
  307. x := int(i >> log2WordSize)
  308. if x >= len(b.set) || capacity == 0 {
  309. return 0, myanswer[:0]
  310. }
  311. skip := i & (wordSize - 1)
  312. word := b.set[x] >> skip
  313. myanswer = myanswer[:capacity]
  314. size := int(0)
  315. for word != 0 {
  316. r := trailingZeroes64(word)
  317. t := word & ((^word) + 1)
  318. myanswer[size] = r + i
  319. size++
  320. if size == capacity {
  321. goto End
  322. }
  323. word = word ^ t
  324. }
  325. x++
  326. for idx, word := range b.set[x:] {
  327. for word != 0 {
  328. r := trailingZeroes64(word)
  329. t := word & ((^word) + 1)
  330. myanswer[size] = r + (uint(x+idx) << 6)
  331. size++
  332. if size == capacity {
  333. goto End
  334. }
  335. word = word ^ t
  336. }
  337. }
  338. End:
  339. if size > 0 {
  340. return myanswer[size-1], myanswer[:size]
  341. }
  342. return 0, myanswer[:0]
  343. }
  344. // NextClear returns the next clear bit from the specified index,
  345. // including possibly the current index
  346. // along with an error code (true = valid, false = no bit found i.e. all bits are set)
  347. func (b *BitSet) NextClear(i uint) (uint, bool) {
  348. x := int(i >> log2WordSize)
  349. if x >= len(b.set) {
  350. return 0, false
  351. }
  352. w := b.set[x]
  353. w = w >> (i & (wordSize - 1))
  354. wA := allBits >> (i & (wordSize - 1))
  355. index := i + trailingZeroes64(^w)
  356. if w != wA && index < b.length {
  357. return index, true
  358. }
  359. x++
  360. for x < len(b.set) {
  361. index = uint(x)*wordSize + trailingZeroes64(^b.set[x])
  362. if b.set[x] != allBits && index < b.length {
  363. return index, true
  364. }
  365. x++
  366. }
  367. return 0, false
  368. }
  369. // ClearAll clears the entire BitSet
  370. func (b *BitSet) ClearAll() *BitSet {
  371. if b != nil && b.set != nil {
  372. for i := range b.set {
  373. b.set[i] = 0
  374. }
  375. }
  376. return b
  377. }
  378. // wordCount returns the number of words used in a bit set
  379. func (b *BitSet) wordCount() int {
  380. return len(b.set)
  381. }
  382. // Clone this BitSet
  383. func (b *BitSet) Clone() *BitSet {
  384. c := New(b.length)
  385. if b.set != nil { // Clone should not modify current object
  386. copy(c.set, b.set)
  387. }
  388. return c
  389. }
  390. // Copy into a destination BitSet
  391. // Returning the size of the destination BitSet
  392. // like array copy
  393. func (b *BitSet) Copy(c *BitSet) (count uint) {
  394. if c == nil {
  395. return
  396. }
  397. if b.set != nil { // Copy should not modify current object
  398. copy(c.set, b.set)
  399. }
  400. count = c.length
  401. if b.length < c.length {
  402. count = b.length
  403. }
  404. return
  405. }
  406. // Count (number of set bits)
  407. func (b *BitSet) Count() uint {
  408. if b != nil && b.set != nil {
  409. return uint(popcntSlice(b.set))
  410. }
  411. return 0
  412. }
  413. // Equal tests the equvalence of two BitSets.
  414. // False if they are of different sizes, otherwise true
  415. // only if all the same bits are set
  416. func (b *BitSet) Equal(c *BitSet) bool {
  417. if c == nil {
  418. return false
  419. }
  420. if b.length != c.length {
  421. return false
  422. }
  423. if b.length == 0 { // if they have both length == 0, then could have nil set
  424. return true
  425. }
  426. // testing for equality shoud not transform the bitset (no call to safeSet)
  427. for p, v := range b.set {
  428. if c.set[p] != v {
  429. return false
  430. }
  431. }
  432. return true
  433. }
  434. func panicIfNull(b *BitSet) {
  435. if b == nil {
  436. panic(Error("BitSet must not be null"))
  437. }
  438. }
  439. // Difference of base set and other set
  440. // This is the BitSet equivalent of &^ (and not)
  441. func (b *BitSet) Difference(compare *BitSet) (result *BitSet) {
  442. panicIfNull(b)
  443. panicIfNull(compare)
  444. result = b.Clone() // clone b (in case b is bigger than compare)
  445. l := int(compare.wordCount())
  446. if l > int(b.wordCount()) {
  447. l = int(b.wordCount())
  448. }
  449. for i := 0; i < l; i++ {
  450. result.set[i] = b.set[i] &^ compare.set[i]
  451. }
  452. return
  453. }
  454. // DifferenceCardinality computes the cardinality of the differnce
  455. func (b *BitSet) DifferenceCardinality(compare *BitSet) uint {
  456. panicIfNull(b)
  457. panicIfNull(compare)
  458. l := int(compare.wordCount())
  459. if l > int(b.wordCount()) {
  460. l = int(b.wordCount())
  461. }
  462. cnt := uint64(0)
  463. cnt += popcntMaskSlice(b.set[:l], compare.set[:l])
  464. cnt += popcntSlice(b.set[l:])
  465. return uint(cnt)
  466. }
  467. // InPlaceDifference computes the difference of base set and other set
  468. // This is the BitSet equivalent of &^ (and not)
  469. func (b *BitSet) InPlaceDifference(compare *BitSet) {
  470. panicIfNull(b)
  471. panicIfNull(compare)
  472. l := int(compare.wordCount())
  473. if l > int(b.wordCount()) {
  474. l = int(b.wordCount())
  475. }
  476. for i := 0; i < l; i++ {
  477. b.set[i] &^= compare.set[i]
  478. }
  479. }
  480. // Convenience function: return two bitsets ordered by
  481. // increasing length. Note: neither can be nil
  482. func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) {
  483. if a.length <= b.length {
  484. ap, bp = a, b
  485. } else {
  486. ap, bp = b, a
  487. }
  488. return
  489. }
  490. // Intersection of base set and other set
  491. // This is the BitSet equivalent of & (and)
  492. func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) {
  493. panicIfNull(b)
  494. panicIfNull(compare)
  495. b, compare = sortByLength(b, compare)
  496. result = New(b.length)
  497. for i, word := range b.set {
  498. result.set[i] = word & compare.set[i]
  499. }
  500. return
  501. }
  502. // IntersectionCardinality computes the cardinality of the union
  503. func (b *BitSet) IntersectionCardinality(compare *BitSet) uint {
  504. panicIfNull(b)
  505. panicIfNull(compare)
  506. b, compare = sortByLength(b, compare)
  507. cnt := popcntAndSlice(b.set, compare.set)
  508. return uint(cnt)
  509. }
  510. // InPlaceIntersection destructively computes the intersection of
  511. // base set and the compare set.
  512. // This is the BitSet equivalent of & (and)
  513. func (b *BitSet) InPlaceIntersection(compare *BitSet) {
  514. panicIfNull(b)
  515. panicIfNull(compare)
  516. l := int(compare.wordCount())
  517. if l > int(b.wordCount()) {
  518. l = int(b.wordCount())
  519. }
  520. for i := 0; i < l; i++ {
  521. b.set[i] &= compare.set[i]
  522. }
  523. for i := l; i < len(b.set); i++ {
  524. b.set[i] = 0
  525. }
  526. if compare.length > 0 {
  527. b.extendSetMaybe(compare.length - 1)
  528. }
  529. }
  530. // Union of base set and other set
  531. // This is the BitSet equivalent of | (or)
  532. func (b *BitSet) Union(compare *BitSet) (result *BitSet) {
  533. panicIfNull(b)
  534. panicIfNull(compare)
  535. b, compare = sortByLength(b, compare)
  536. result = compare.Clone()
  537. for i, word := range b.set {
  538. result.set[i] = word | compare.set[i]
  539. }
  540. return
  541. }
  542. // UnionCardinality computes the cardinality of the uniton of the base set
  543. // and the compare set.
  544. func (b *BitSet) UnionCardinality(compare *BitSet) uint {
  545. panicIfNull(b)
  546. panicIfNull(compare)
  547. b, compare = sortByLength(b, compare)
  548. cnt := popcntOrSlice(b.set, compare.set)
  549. if len(compare.set) > len(b.set) {
  550. cnt += popcntSlice(compare.set[len(b.set):])
  551. }
  552. return uint(cnt)
  553. }
  554. // InPlaceUnion creates the destructive union of base set and compare set.
  555. // This is the BitSet equivalent of | (or).
  556. func (b *BitSet) InPlaceUnion(compare *BitSet) {
  557. panicIfNull(b)
  558. panicIfNull(compare)
  559. l := int(compare.wordCount())
  560. if l > int(b.wordCount()) {
  561. l = int(b.wordCount())
  562. }
  563. if compare.length > 0 {
  564. b.extendSetMaybe(compare.length - 1)
  565. }
  566. for i := 0; i < l; i++ {
  567. b.set[i] |= compare.set[i]
  568. }
  569. if len(compare.set) > l {
  570. for i := l; i < len(compare.set); i++ {
  571. b.set[i] = compare.set[i]
  572. }
  573. }
  574. }
  575. // SymmetricDifference of base set and other set
  576. // This is the BitSet equivalent of ^ (xor)
  577. func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) {
  578. panicIfNull(b)
  579. panicIfNull(compare)
  580. b, compare = sortByLength(b, compare)
  581. // compare is bigger, so clone it
  582. result = compare.Clone()
  583. for i, word := range b.set {
  584. result.set[i] = word ^ compare.set[i]
  585. }
  586. return
  587. }
  588. // SymmetricDifferenceCardinality computes the cardinality of the symmetric difference
  589. func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint {
  590. panicIfNull(b)
  591. panicIfNull(compare)
  592. b, compare = sortByLength(b, compare)
  593. cnt := popcntXorSlice(b.set, compare.set)
  594. if len(compare.set) > len(b.set) {
  595. cnt += popcntSlice(compare.set[len(b.set):])
  596. }
  597. return uint(cnt)
  598. }
  599. // InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set
  600. // This is the BitSet equivalent of ^ (xor)
  601. func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) {
  602. panicIfNull(b)
  603. panicIfNull(compare)
  604. l := int(compare.wordCount())
  605. if l > int(b.wordCount()) {
  606. l = int(b.wordCount())
  607. }
  608. if compare.length > 0 {
  609. b.extendSetMaybe(compare.length - 1)
  610. }
  611. for i := 0; i < l; i++ {
  612. b.set[i] ^= compare.set[i]
  613. }
  614. if len(compare.set) > l {
  615. for i := l; i < len(compare.set); i++ {
  616. b.set[i] = compare.set[i]
  617. }
  618. }
  619. }
  620. // Is the length an exact multiple of word sizes?
  621. func (b *BitSet) isLenExactMultiple() bool {
  622. return b.length%wordSize == 0
  623. }
  624. // Clean last word by setting unused bits to 0
  625. func (b *BitSet) cleanLastWord() {
  626. if !b.isLenExactMultiple() {
  627. b.set[len(b.set)-1] &= allBits >> (wordSize - b.length%wordSize)
  628. }
  629. }
  630. // Complement computes the (local) complement of a biset (up to length bits)
  631. func (b *BitSet) Complement() (result *BitSet) {
  632. panicIfNull(b)
  633. result = New(b.length)
  634. for i, word := range b.set {
  635. result.set[i] = ^word
  636. }
  637. result.cleanLastWord()
  638. return
  639. }
  640. // All returns true if all bits are set, false otherwise. Returns true for
  641. // empty sets.
  642. func (b *BitSet) All() bool {
  643. panicIfNull(b)
  644. return b.Count() == b.length
  645. }
  646. // None returns true if no bit is set, false otherwise. Retursn true for
  647. // empty sets.
  648. func (b *BitSet) None() bool {
  649. panicIfNull(b)
  650. if b != nil && b.set != nil {
  651. for _, word := range b.set {
  652. if word > 0 {
  653. return false
  654. }
  655. }
  656. return true
  657. }
  658. return true
  659. }
  660. // Any returns true if any bit is set, false otherwise
  661. func (b *BitSet) Any() bool {
  662. panicIfNull(b)
  663. return !b.None()
  664. }
  665. // IsSuperSet returns true if this is a superset of the other set
  666. func (b *BitSet) IsSuperSet(other *BitSet) bool {
  667. for i, e := other.NextSet(0); e; i, e = other.NextSet(i + 1) {
  668. if !b.Test(i) {
  669. return false
  670. }
  671. }
  672. return true
  673. }
  674. // IsStrictSuperSet returns true if this is a strict superset of the other set
  675. func (b *BitSet) IsStrictSuperSet(other *BitSet) bool {
  676. return b.Count() > other.Count() && b.IsSuperSet(other)
  677. }
  678. // DumpAsBits dumps a bit set as a string of bits
  679. func (b *BitSet) DumpAsBits() string {
  680. if b.set == nil {
  681. return "."
  682. }
  683. buffer := bytes.NewBufferString("")
  684. i := len(b.set) - 1
  685. for ; i >= 0; i-- {
  686. fmt.Fprintf(buffer, "%064b.", b.set[i])
  687. }
  688. return buffer.String()
  689. }
  690. // BinaryStorageSize returns the binary storage requirements
  691. func (b *BitSet) BinaryStorageSize() int {
  692. return binary.Size(uint64(0)) + binary.Size(b.set)
  693. }
  694. // WriteTo writes a BitSet to a stream
  695. func (b *BitSet) WriteTo(stream io.Writer) (int64, error) {
  696. length := uint64(b.length)
  697. // Write length
  698. err := binary.Write(stream, binaryOrder, length)
  699. if err != nil {
  700. return 0, err
  701. }
  702. // Write set
  703. err = binary.Write(stream, binaryOrder, b.set)
  704. return int64(b.BinaryStorageSize()), err
  705. }
  706. // ReadFrom reads a BitSet from a stream written using WriteTo
  707. func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) {
  708. var length uint64
  709. // Read length first
  710. err := binary.Read(stream, binaryOrder, &length)
  711. if err != nil {
  712. return 0, err
  713. }
  714. newset := New(uint(length))
  715. if uint64(newset.length) != length {
  716. return 0, errors.New("Unmarshalling error: type mismatch")
  717. }
  718. // Read remaining bytes as set
  719. err = binary.Read(stream, binaryOrder, newset.set)
  720. if err != nil {
  721. return 0, err
  722. }
  723. *b = *newset
  724. return int64(b.BinaryStorageSize()), nil
  725. }
  726. // MarshalBinary encodes a BitSet into a binary form and returns the result.
  727. func (b *BitSet) MarshalBinary() ([]byte, error) {
  728. var buf bytes.Buffer
  729. writer := bufio.NewWriter(&buf)
  730. _, err := b.WriteTo(writer)
  731. if err != nil {
  732. return []byte{}, err
  733. }
  734. err = writer.Flush()
  735. return buf.Bytes(), err
  736. }
  737. // UnmarshalBinary decodes the binary form generated by MarshalBinary.
  738. func (b *BitSet) UnmarshalBinary(data []byte) error {
  739. buf := bytes.NewReader(data)
  740. reader := bufio.NewReader(buf)
  741. _, err := b.ReadFrom(reader)
  742. return err
  743. }
  744. // MarshalJSON marshals a BitSet as a JSON structure
  745. func (b *BitSet) MarshalJSON() ([]byte, error) {
  746. buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize()))
  747. _, err := b.WriteTo(buffer)
  748. if err != nil {
  749. return nil, err
  750. }
  751. // URLEncode all bytes
  752. return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes()))
  753. }
  754. // UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON
  755. func (b *BitSet) UnmarshalJSON(data []byte) error {
  756. // Unmarshal as string
  757. var s string
  758. err := json.Unmarshal(data, &s)
  759. if err != nil {
  760. return err
  761. }
  762. // URLDecode string
  763. buf, err := base64Encoding.DecodeString(s)
  764. if err != nil {
  765. return err
  766. }
  767. _, err = b.ReadFrom(bytes.NewReader(buf))
  768. return err
  769. }