Debian Codegraph @

container/intsets/sparse.go

raw symbols SCIP
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package intsets provides Sparse, a compact and fast representation
6 // for sparse sets of int values.
7 //
8 // The time complexity of the operations Len, Insert, Remove and Has
9 // is in O(n) but in practice those methods are faster and more
10 // space-efficient than equivalent operations on sets based on the Go
11 // map type. The IsEmpty, Min, Max, Clear and TakeMin operations
12 // require constant time.
13 package intsets // import "golang.org/x/tools/container/intsets"
14
15 // TODO(adonovan):
16 // - Add InsertAll(...int), RemoveAll(...int)
17 // - Add 'bool changed' results for {Intersection,Difference}With too.
18 //
19 // TODO(adonovan): implement Dense, a dense bit vector with a similar API.
20 // The space usage would be proportional to Max(), not Len(), and the
21 // implementation would be based upon big.Int.
22 //
23 // TODO(adonovan): opt: make UnionWith and Difference faster.
24 // These are the hot-spots for go/pointer.
25
26 import (
27 "bytes"
28 "fmt"
29 "math/bits"
30 )
31
32 // A Sparse is a set of int values.
33 // Sparse operations (even queries) are not concurrency-safe.
34 //
35 // The zero value for Sparse is a valid empty set.
36 //
37 // Sparse sets must be copied using the Copy method, not by assigning
38 // a Sparse value.
39 type Sparse struct {
40 // An uninitialized Sparse represents an empty set.
41 // An empty set may also be represented by
42 // root.next == root.prev == &root.
43 //
44 // The root is always the block with the smallest offset.
45 // It can be empty, but only if it is the only block; in that case, offset is
46 // MaxInt (which is not a valid offset).
47 root block
48 }
49
50 type word uintptr
51
52 const (
53 _m = ^word(0)
54 bitsPerWord = 8 << (_m>>8&1 + _m>>16&1 + _m>>32&1)
55 bitsPerBlock = 256 // optimal value for go/pointer solver performance
56 wordsPerBlock = bitsPerBlock / bitsPerWord
57 )
58
59 // Limit values of implementation-specific int type.
60 const (
61 MaxInt = int(^uint(0) >> 1)
62 MinInt = -MaxInt - 1
63 )
64
65 // popcount returns the number of set bits in w.
66 func popcount(x word) int {
67 // Avoid OnesCount(uint): don't assume uint = uintptr.
68 if bitsPerWord == 32 {
69 return bits.OnesCount32(uint32(x))
70 } else {
71 return bits.OnesCount64(uint64(x))
72 }
73 }
74
75 // nlz returns the number of leading zeros of x.
76 func nlz(x word) int {
77 // Avoid LeadingZeros(uint): don't assume uint = uintptr.
78 if bitsPerWord == 32 {
79 return bits.LeadingZeros32(uint32(x))
80 } else {
81 return bits.LeadingZeros64(uint64(x))
82 }
83 }
84
85 // ntz returns the number of trailing zeros of x.
86 func ntz(x word) int {
87 // Avoid TrailingZeros(uint): don't assume uint = uintptr.
88 if bitsPerWord == 32 {
89 return bits.TrailingZeros32(uint32(x))
90 } else {
91 return bits.TrailingZeros64(uint64(x))
92 }
93 }
94
95 // -- block ------------------------------------------------------------
96
97 // A set is represented as a circular doubly-linked list of blocks,
98 // each containing an offset and a bit array of fixed size
99 // bitsPerBlock; the blocks are ordered by increasing offset.
100 //
101 // The set contains an element x iff the block whose offset is x - (x
102 // mod bitsPerBlock) has the bit (x mod bitsPerBlock) set, where mod
103 // is the Euclidean remainder.
104 //
105 // A block may only be empty transiently.
106 type block struct {
107 offset int // offset mod bitsPerBlock == 0
108 bits [wordsPerBlock]word // contains at least one set bit
109 next, prev *block // doubly-linked list of blocks
110 }
111
112 // wordMask returns the word index (in block.bits)
113 // and single-bit mask for the block's ith bit.
114 func wordMask(i uint) (w uint, mask word) {
115 w = i / bitsPerWord
116 mask = 1 << (i % bitsPerWord)
117 return
118 }
119
120 // insert sets the block b's ith bit and
121 // returns true if it was not already set.
122 func (b *block) insert(i uint) bool {
123 w, mask := wordMask(i)
124 if b.bits[w]&mask == 0 {
125 b.bits[w] |= mask
126 return true
127 }
128 return false
129 }
130
131 // remove clears the block's ith bit and
132 // returns true if the bit was previously set.
133 // NB: may leave the block empty.
134 func (b *block) remove(i uint) bool {
135 w, mask := wordMask(i)
136 if b.bits[w]&mask != 0 {
137 b.bits[w] &^= mask
138 return true
139 }
140 return false
141 }
142
143 // has reports whether the block's ith bit is set.
144 func (b *block) has(i uint) bool {
145 w, mask := wordMask(i)
146 return b.bits[w]&mask != 0
147 }
148
149 // empty reports whether b.len()==0, but more efficiently.
150 func (b *block) empty() bool {
151 for _, w := range b.bits {
152 if w != 0 {
153 return false
154 }
155 }
156 return true
157 }
158
159 // len returns the number of set bits in block b.
160 func (b *block) len() int {
161 var l int
162 for _, w := range b.bits {
163 l += popcount(w)
164 }
165 return l
166 }
167
168 // max returns the maximum element of the block.
169 // The block must not be empty.
170 func (b *block) max() int {
171 bi := b.offset + bitsPerBlock
172 // Decrement bi by number of high zeros in last.bits.
173 for i := len(b.bits) - 1; i >= 0; i-- {
174 if w := b.bits[i]; w != 0 {
175 return bi - nlz(w) - 1
176 }
177 bi -= bitsPerWord
178 }
179 panic("BUG: empty block")
180 }
181
182 // min returns the minimum element of the block,
183 // and also removes it if take is set.
184 // The block must not be initially empty.
185 // NB: may leave the block empty.
186 func (b *block) min(take bool) int {
187 for i, w := range b.bits {
188 if w != 0 {
189 tz := ntz(w)
190 if take {
191 b.bits[i] = w &^ (1 << uint(tz))
192 }
193 return b.offset + i*bitsPerWord + tz
194 }
195 }
196 panic("BUG: empty block")
197 }
198
199 // lowerBound returns the smallest element of the block that is greater than or
200 // equal to the element corresponding to the ith bit. If there is no such
201 // element, the second return value is false.
202 func (b *block) lowerBound(i uint) (int, bool) {
203 w := i / bitsPerWord
204 bit := i % bitsPerWord
205
206 if val := b.bits[w] >> bit; val != 0 {
207 return b.offset + int(i) + ntz(val), true
208 }
209
210 for w++; w < wordsPerBlock; w++ {
211 if val := b.bits[w]; val != 0 {
212 return b.offset + int(w*bitsPerWord) + ntz(val), true
213 }
214 }
215
216 return 0, false
217 }
218
219 // forEach calls f for each element of block b.
220 // f must not mutate b's enclosing Sparse.
221 func (b *block) forEach(f func(int)) {
222 for i, w := range b.bits {
223 offset := b.offset + i*bitsPerWord
224 for bi := 0; w != 0 && bi < bitsPerWord; bi++ {
225 if w&1 != 0 {
226 f(offset)
227 }
228 offset++
229 w >>= 1
230 }
231 }
232 }
233
234 // offsetAndBitIndex returns the offset of the block that would
235 // contain x and the bit index of x within that block.
236 func offsetAndBitIndex(x int) (int, uint) {
237 mod := x % bitsPerBlock
238 if mod < 0 {
239 // Euclidean (non-negative) remainder
240 mod += bitsPerBlock
241 }
242 return x - mod, uint(mod)
243 }
244
245 // -- Sparse --------------------------------------------------------------
246
247 // none is a shared, empty, sentinel block that indicates the end of a block
248 // list.
249 var none block
250
251 // Dummy type used to generate an implicit panic. This must be defined at the
252 // package level; if it is defined inside a function, it prevents the inlining
253 // of that function.
254 type to_copy_a_sparse_you_must_call_its_Copy_method struct{}
255
256 // init ensures s is properly initialized.
257 func (s *Sparse) init() {
258 root := &s.root
259 if root.next == nil {
260 root.offset = MaxInt
261 root.next = root
262 root.prev = root
263 } else if root.next.prev != root {
264 // Copying a Sparse x leads to pernicious corruption: the
265 // new Sparse y shares the old linked list, but iteration
266 // on y will never encounter &y.root so it goes into a
267 // loop. Fail fast before this occurs.
268 // We don't want to call panic here because it prevents the
269 // inlining of this function.
270 _ = (any(nil)).(to_copy_a_sparse_you_must_call_its_Copy_method)
271 }
272 }
273
274 func (s *Sparse) first() *block {
275 s.init()
276 if s.root.offset == MaxInt {
277 return &none
278 }
279 return &s.root
280 }
281
282 // next returns the next block in the list, or end if b is the last block.
283 func (s *Sparse) next(b *block) *block {
284 if b.next == &s.root {
285 return &none
286 }
287 return b.next
288 }
289
290 // IsEmpty reports whether the set s is empty.
291 func (s *Sparse) IsEmpty() bool {
292 return s.root.next == nil || s.root.offset == MaxInt
293 }
294
295 // Len returns the number of elements in the set s.
296 func (s *Sparse) Len() int {
297 var l int
298 for b := s.first(); b != &none; b = s.next(b) {
299 l += b.len()
300 }
301 return l
302 }
303
304 // Max returns the maximum element of the set s, or MinInt if s is empty.
305 func (s *Sparse) Max() int {
306 if s.IsEmpty() {
307 return MinInt
308 }
309 return s.root.prev.max()
310 }
311
312 // Min returns the minimum element of the set s, or MaxInt if s is empty.
313 func (s *Sparse) Min() int {
314 if s.IsEmpty() {
315 return MaxInt
316 }
317 return s.root.min(false)
318 }
319
320 // LowerBound returns the smallest element >= x, or MaxInt if there is no such
321 // element.
322 func (s *Sparse) LowerBound(x int) int {
323 offset, i := offsetAndBitIndex(x)
324 for b := s.first(); b != &none; b = s.next(b) {
325 if b.offset > offset {
326 return b.min(false)
327 }
328 if b.offset == offset {
329 if y, ok := b.lowerBound(i); ok {
330 return y
331 }
332 }
333 }
334 return MaxInt
335 }
336
337 // block returns the block that would contain offset,
338 // or nil if s contains no such block.
339 // Precondition: offset is a multiple of bitsPerBlock.
340 func (s *Sparse) block(offset int) *block {
341 for b := s.first(); b != &none && b.offset <= offset; b = s.next(b) {
342 if b.offset == offset {
343 return b
344 }
345 }
346 return nil
347 }
348
349 // Insert adds x to the set s, and reports whether the set grew.
350 func (s *Sparse) Insert(x int) bool {
351 offset, i := offsetAndBitIndex(x)
352
353 b := s.first()
354 for ; b != &none && b.offset <= offset; b = s.next(b) {
355 if b.offset == offset {
356 return b.insert(i)
357 }
358 }
359
360 // Insert new block before b.
361 new := s.insertBlockBefore(b)
362 new.offset = offset
363 return new.insert(i)
364 }
365
366 // removeBlock removes a block and returns the block that followed it (or end if
367 // it was the last block).
368 func (s *Sparse) removeBlock(b *block) *block {
369 if b != &s.root {
370 b.prev.next = b.next
371 b.next.prev = b.prev
372 if b.next == &s.root {
373 return &none
374 }
375 return b.next
376 }
377
378 first := s.root.next
379 if first == &s.root {
380 // This was the only block.
381 s.Clear()
382 return &none
383 }
384 s.root.offset = first.offset
385 s.root.bits = first.bits
386 if first.next == &s.root {
387 // Single block remaining.
388 s.root.next = &s.root
389 s.root.prev = &s.root
390 } else {
391 s.root.next = first.next
392 first.next.prev = &s.root
393 }
394 return &s.root
395 }
396
397 // Remove removes x from the set s, and reports whether the set shrank.
398 func (s *Sparse) Remove(x int) bool {
399 offset, i := offsetAndBitIndex(x)
400 if b := s.block(offset); b != nil {
401 if !b.remove(i) {
402 return false
403 }
404 if b.empty() {
405 s.removeBlock(b)
406 }
407 return true
408 }
409 return false
410 }
411
412 // Clear removes all elements from the set s.
413 func (s *Sparse) Clear() {
414 s.root = block{
415 offset: MaxInt,
416 next: &s.root,
417 prev: &s.root,
418 }
419 }
420
421 // If set s is non-empty, TakeMin sets *p to the minimum element of
422 // the set s, removes that element from the set and returns true.
423 // Otherwise, it returns false and *p is undefined.
424 //
425 // This method may be used for iteration over a worklist like so:
426 //
427 // var x int
428 // for worklist.TakeMin(&x) { use(x) }
429 func (s *Sparse) TakeMin(p *int) bool {
430 if s.IsEmpty() {
431 return false
432 }
433 *p = s.root.min(true)
434 if s.root.empty() {
435 s.removeBlock(&s.root)
436 }
437 return true
438 }
439
440 // Has reports whether x is an element of the set s.
441 func (s *Sparse) Has(x int) bool {
442 offset, i := offsetAndBitIndex(x)
443 if b := s.block(offset); b != nil {
444 return b.has(i)
445 }
446 return false
447 }
448
449 // forEach applies function f to each element of the set s in order.
450 //
451 // f must not mutate s. Consequently, forEach is not safe to expose
452 // to clients. In any case, using "range s.AppendTo()" allows more
453 // natural control flow with continue/break/return.
454 func (s *Sparse) forEach(f func(int)) {
455 for b := s.first(); b != &none; b = s.next(b) {
456 b.forEach(f)
457 }
458 }
459
460 // Copy sets s to the value of x.
461 func (s *Sparse) Copy(x *Sparse) {
462 if s == x {
463 return
464 }
465
466 xb := x.first()
467 sb := s.first()
468 for xb != &none {
469 if sb == &none {
470 sb = s.insertBlockBefore(sb)
471 }
472 sb.offset = xb.offset
473 sb.bits = xb.bits
474 xb = x.next(xb)
475 sb = s.next(sb)
476 }
477 s.discardTail(sb)
478 }
479
480 // insertBlockBefore returns a new block, inserting it before next.
481 // If next is the root, the root is replaced. If next is end, the block is
482 // inserted at the end.
483 func (s *Sparse) insertBlockBefore(next *block) *block {
484 if s.IsEmpty() {
485 if next != &none {
486 panic("BUG: passed block with empty set")
487 }
488 return &s.root
489 }
490
491 if next == &s.root {
492 // Special case: we need to create a new block that will become the root
493 // block.The old root block becomes the second block.
494 second := s.root
495 s.root = block{
496 next: &second,
497 }
498 if second.next == &s.root {
499 s.root.prev = &second
500 } else {
501 s.root.prev = second.prev
502 second.next.prev = &second
503 second.prev = &s.root
504 }
505 return &s.root
506 }
507 if next == &none {
508 // Insert before root.
509 next = &s.root
510 }
511 b := new(block)
512 b.next = next
513 b.prev = next.prev
514 b.prev.next = b
515 next.prev = b
516 return b
517 }
518
519 // discardTail removes block b and all its successors from s.
520 func (s *Sparse) discardTail(b *block) {
521 if b != &none {
522 if b == &s.root {
523 s.Clear()
524 } else {
525 b.prev.next = &s.root
526 s.root.prev = b.prev
527 }
528 }
529 }
530
531 // IntersectionWith sets s to the intersection s ∩ x.
532 func (s *Sparse) IntersectionWith(x *Sparse) {
533 if s == x {
534 return
535 }
536
537 xb := x.first()
538 sb := s.first()
539 for xb != &none && sb != &none {
540 switch {
541 case xb.offset < sb.offset:
542 xb = x.next(xb)
543
544 case xb.offset > sb.offset:
545 sb = s.removeBlock(sb)
546
547 default:
548 var sum word
549 for i := range sb.bits {
550 r := xb.bits[i] & sb.bits[i]
551 sb.bits[i] = r
552 sum |= r
553 }
554 if sum != 0 {
555 sb = s.next(sb)
556 } else {
557 // sb will be overwritten or removed
558 }
559
560 xb = x.next(xb)
561 }
562 }
563
564 s.discardTail(sb)
565 }
566
567 // Intersection sets s to the intersection x ∩ y.
568 func (s *Sparse) Intersection(x, y *Sparse) {
569 switch {
570 case s == x:
571 s.IntersectionWith(y)
572 return
573 case s == y:
574 s.IntersectionWith(x)
575 return
576 case x == y:
577 s.Copy(x)
578 return
579 }
580
581 xb := x.first()
582 yb := y.first()
583 sb := s.first()
584 for xb != &none && yb != &none {
585 switch {
586 case xb.offset < yb.offset:
587 xb = x.next(xb)
588 continue
589 case xb.offset > yb.offset:
590 yb = y.next(yb)
591 continue
592 }
593
594 if sb == &none {
595 sb = s.insertBlockBefore(sb)
596 }
597 sb.offset = xb.offset
598
599 var sum word
600 for i := range sb.bits {
601 r := xb.bits[i] & yb.bits[i]
602 sb.bits[i] = r
603 sum |= r
604 }
605 if sum != 0 {
606 sb = s.next(sb)
607 } else {
608 // sb will be overwritten or removed
609 }
610
611 xb = x.next(xb)
612 yb = y.next(yb)
613 }
614
615 s.discardTail(sb)
616 }
617
618 // Intersects reports whether s ∩ x ≠ ∅.
619 func (s *Sparse) Intersects(x *Sparse) bool {
620 sb := s.first()
621 xb := x.first()
622 for sb != &none && xb != &none {
623 switch {
624 case xb.offset < sb.offset:
625 xb = x.next(xb)
626 case xb.offset > sb.offset:
627 sb = s.next(sb)
628 default:
629 for i := range sb.bits {
630 if sb.bits[i]&xb.bits[i] != 0 {
631 return true
632 }
633 }
634 sb = s.next(sb)
635 xb = x.next(xb)
636 }
637 }
638 return false
639 }
640
641 // UnionWith sets s to the union s ∪ x, and reports whether s grew.
642 func (s *Sparse) UnionWith(x *Sparse) bool {
643 if s == x {
644 return false
645 }
646
647 var changed bool
648 xb := x.first()
649 sb := s.first()
650 for xb != &none {
651 if sb != &none && sb.offset == xb.offset {
652 for i := range xb.bits {
653 union := sb.bits[i] | xb.bits[i]
654 if sb.bits[i] != union {
655 sb.bits[i] = union
656 changed = true
657 }
658 }
659 xb = x.next(xb)
660 } else if sb == &none || sb.offset > xb.offset {
661 sb = s.insertBlockBefore(sb)
662 sb.offset = xb.offset
663 sb.bits = xb.bits
664 changed = true
665
666 xb = x.next(xb)
667 }
668 sb = s.next(sb)
669 }
670 return changed
671 }
672
673 // Union sets s to the union x ∪ y.
674 func (s *Sparse) Union(x, y *Sparse) {
675 switch {
676 case x == y:
677 s.Copy(x)
678 return
679 case s == x:
680 s.UnionWith(y)
681 return
682 case s == y:
683 s.UnionWith(x)
684 return
685 }
686
687 xb := x.first()
688 yb := y.first()
689 sb := s.first()
690 for xb != &none || yb != &none {
691 if sb == &none {
692 sb = s.insertBlockBefore(sb)
693 }
694 switch {
695 case yb == &none || (xb != &none && xb.offset < yb.offset):
696 sb.offset = xb.offset
697 sb.bits = xb.bits
698 xb = x.next(xb)
699
700 case xb == &none || (yb != &none && yb.offset < xb.offset):
701 sb.offset = yb.offset
702 sb.bits = yb.bits
703 yb = y.next(yb)
704
705 default:
706 sb.offset = xb.offset
707 for i := range xb.bits {
708 sb.bits[i] = xb.bits[i] | yb.bits[i]
709 }
710 xb = x.next(xb)
711 yb = y.next(yb)
712 }
713 sb = s.next(sb)
714 }
715
716 s.discardTail(sb)
717 }
718
719 // DifferenceWith sets s to the difference s ∖ x.
720 func (s *Sparse) DifferenceWith(x *Sparse) {
721 if s == x {
722 s.Clear()
723 return
724 }
725
726 xb := x.first()
727 sb := s.first()
728 for xb != &none && sb != &none {
729 switch {
730 case xb.offset > sb.offset:
731 sb = s.next(sb)
732
733 case xb.offset < sb.offset:
734 xb = x.next(xb)
735
736 default:
737 var sum word
738 for i := range sb.bits {
739 r := sb.bits[i] & ^xb.bits[i]
740 sb.bits[i] = r
741 sum |= r
742 }
743 if sum == 0 {
744 sb = s.removeBlock(sb)
745 } else {
746 sb = s.next(sb)
747 }
748 xb = x.next(xb)
749 }
750 }
751 }
752
753 // Difference sets s to the difference x ∖ y.
754 func (s *Sparse) Difference(x, y *Sparse) {
755 switch {
756 case x == y:
757 s.Clear()
758 return
759 case s == x:
760 s.DifferenceWith(y)
761 return
762 case s == y:
763 var y2 Sparse
764 y2.Copy(y)
765 s.Difference(x, &y2)
766 return
767 }
768
769 xb := x.first()
770 yb := y.first()
771 sb := s.first()
772 for xb != &none && yb != &none {
773 if xb.offset > yb.offset {
774 // y has block, x has &none
775 yb = y.next(yb)
776 continue
777 }
778
779 if sb == &none {
780 sb = s.insertBlockBefore(sb)
781 }
782 sb.offset = xb.offset
783
784 switch {
785 case xb.offset < yb.offset:
786 // x has block, y has &none
787 sb.bits = xb.bits
788
789 sb = s.next(sb)
790
791 default:
792 // x and y have corresponding blocks
793 var sum word
794 for i := range sb.bits {
795 r := xb.bits[i] & ^yb.bits[i]
796 sb.bits[i] = r
797 sum |= r
798 }
799 if sum != 0 {
800 sb = s.next(sb)
801 } else {
802 // sb will be overwritten or removed
803 }
804
805 yb = y.next(yb)
806 }
807 xb = x.next(xb)
808 }
809
810 for xb != &none {
811 if sb == &none {
812 sb = s.insertBlockBefore(sb)
813 }
814 sb.offset = xb.offset
815 sb.bits = xb.bits
816 sb = s.next(sb)
817
818 xb = x.next(xb)
819 }
820
821 s.discardTail(sb)
822 }
823
824 // SymmetricDifferenceWith sets s to the symmetric difference s ∆ x.
825 func (s *Sparse) SymmetricDifferenceWith(x *Sparse) {
826 if s == x {
827 s.Clear()
828 return
829 }
830
831 sb := s.first()
832 xb := x.first()
833 for xb != &none && sb != &none {
834 switch {
835 case sb.offset < xb.offset:
836 sb = s.next(sb)
837 case xb.offset < sb.offset:
838 nb := s.insertBlockBefore(sb)
839 nb.offset = xb.offset
840 nb.bits = xb.bits
841 xb = x.next(xb)
842 default:
843 var sum word
844 for i := range sb.bits {
845 r := sb.bits[i] ^ xb.bits[i]
846 sb.bits[i] = r
847 sum |= r
848 }
849 if sum == 0 {
850 sb = s.removeBlock(sb)
851 } else {
852 sb = s.next(sb)
853 }
854 xb = x.next(xb)
855 }
856 }
857
858 for xb != &none { // append the tail of x to s
859 sb = s.insertBlockBefore(sb)
860 sb.offset = xb.offset
861 sb.bits = xb.bits
862 sb = s.next(sb)
863 xb = x.next(xb)
864 }
865 }
866
867 // SymmetricDifference sets s to the symmetric difference x ∆ y.
868 func (s *Sparse) SymmetricDifference(x, y *Sparse) {
869 switch {
870 case x == y:
871 s.Clear()
872 return
873 case s == x:
874 s.SymmetricDifferenceWith(y)
875 return
876 case s == y:
877 s.SymmetricDifferenceWith(x)
878 return
879 }
880
881 sb := s.first()
882 xb := x.first()
883 yb := y.first()
884 for xb != &none && yb != &none {
885 if sb == &none {
886 sb = s.insertBlockBefore(sb)
887 }
888 switch {
889 case yb.offset < xb.offset:
890 sb.offset = yb.offset
891 sb.bits = yb.bits
892 sb = s.next(sb)
893 yb = y.next(yb)
894 case xb.offset < yb.offset:
895 sb.offset = xb.offset
896 sb.bits = xb.bits
897 sb = s.next(sb)
898 xb = x.next(xb)
899 default:
900 var sum word
901 for i := range sb.bits {
902 r := xb.bits[i] ^ yb.bits[i]
903 sb.bits[i] = r
904 sum |= r
905 }
906 if sum != 0 {
907 sb.offset = xb.offset
908 sb = s.next(sb)
909 }
910 xb = x.next(xb)
911 yb = y.next(yb)
912 }
913 }
914
915 for xb != &none { // append the tail of x to s
916 if sb == &none {
917 sb = s.insertBlockBefore(sb)
918 }
919 sb.offset = xb.offset
920 sb.bits = xb.bits
921 sb = s.next(sb)
922 xb = x.next(xb)
923 }
924
925 for yb != &none { // append the tail of y to s
926 if sb == &none {
927 sb = s.insertBlockBefore(sb)
928 }
929 sb.offset = yb.offset
930 sb.bits = yb.bits
931 sb = s.next(sb)
932 yb = y.next(yb)
933 }
934
935 s.discardTail(sb)
936 }
937
938 // SubsetOf reports whether s ∖ x = ∅.
939 func (s *Sparse) SubsetOf(x *Sparse) bool {
940 if s == x {
941 return true
942 }
943
944 sb := s.first()
945 xb := x.first()
946 for sb != &none {
947 switch {
948 case xb == &none || xb.offset > sb.offset:
949 return false
950 case xb.offset < sb.offset:
951 xb = x.next(xb)
952 default:
953 for i := range sb.bits {
954 if sb.bits[i]&^xb.bits[i] != 0 {
955 return false
956 }
957 }
958 sb = s.next(sb)
959 xb = x.next(xb)
960 }
961 }
962 return true
963 }
964
965 // Equals reports whether the sets s and t have the same elements.
966 func (s *Sparse) Equals(t *Sparse) bool {
967 if s == t {
968 return true
969 }
970 sb := s.first()
971 tb := t.first()
972 for {
973 switch {
974 case sb == &none && tb == &none:
975 return true
976 case sb == &none || tb == &none:
977 return false
978 case sb.offset != tb.offset:
979 return false
980 case sb.bits != tb.bits:
981 return false
982 }
983
984 sb = s.next(sb)
985 tb = t.next(tb)
986 }
987 }
988
989 // String returns a human-readable description of the set s.
990 func (s *Sparse) String() string {
991 var buf bytes.Buffer
992 buf.WriteByte('{')
993 s.forEach(func(x int) {
994 if buf.Len() > 1 {
995 buf.WriteByte(' ')
996 }
997 fmt.Fprintf(&buf, "%d", x)
998 })
999 buf.WriteByte('}')
1000 return buf.String()
1001 }
1002
1003 // BitString returns the set as a string of 1s and 0s denoting the sum
1004 // of the i'th powers of 2, for each i in s. A radix point, always
1005 // preceded by a digit, appears if the sum is non-integral.
1006 //
1007 // Examples:
1008 //
1009 // {}.BitString() = "0"
1010 // {4,5}.BitString() = "110000"
1011 // {-3}.BitString() = "0.001"
1012 // {-3,0,4,5}.BitString() = "110001.001"
1013 func (s *Sparse) BitString() string {
1014 if s.IsEmpty() {
1015 return "0"
1016 }
1017
1018 min, max := s.Min(), s.Max()
1019 var nbytes int
1020 if max > 0 {
1021 nbytes = max
1022 }
1023 nbytes++ // zero bit
1024 radix := nbytes
1025 if min < 0 {
1026 nbytes += len(".") - min
1027 }
1028
1029 b := make([]byte, nbytes)
1030 for i := range b {
1031 b[i] = '0'
1032 }
1033 if radix < nbytes {
1034 b[radix] = '.'
1035 }
1036 s.forEach(func(x int) {
1037 if x >= 0 {
1038 x += len(".")
1039 }
1040 b[radix-x] = '1'
1041 })
1042 return string(b)
1043 }
1044
1045 // GoString returns a string showing the internal representation of
1046 // the set s.
1047 func (s *Sparse) GoString() string {
1048 var buf bytes.Buffer
1049 for b := s.first(); b != &none; b = s.next(b) {
1050 fmt.Fprintf(&buf, "block %p {offset=%d next=%p prev=%p",
1051 b, b.offset, b.next, b.prev)
1052 for _, w := range b.bits {
1053 fmt.Fprintf(&buf, " 0%016x", w)
1054 }
1055 fmt.Fprintf(&buf, "}\n")
1056 }
1057 return buf.String()
1058 }
1059
1060 // AppendTo returns the result of appending the elements of s to slice
1061 // in order.
1062 func (s *Sparse) AppendTo(slice []int) []int {
1063 s.forEach(func(x int) {
1064 slice = append(slice, x)
1065 })
1066 return slice
1067 }
1068
1069 // -- Testing/debugging ------------------------------------------------
1070
1071 // check returns an error if the representation invariants of s are violated.
1072 // (unused; retained for debugging)
1073 func (s *Sparse) check() error {
1074 s.init()
1075 if s.root.empty() {
1076 // An empty set must have only the root block with offset MaxInt.
1077 if s.root.next != &s.root {
1078 return fmt.Errorf("multiple blocks with empty root block")
1079 }
1080 if s.root.offset != MaxInt {
1081 return fmt.Errorf("empty set has offset %d, should be MaxInt", s.root.offset)
1082 }
1083 return nil
1084 }
1085 for b := s.first(); ; b = s.next(b) {
1086 if b.offset%bitsPerBlock != 0 {
1087 return fmt.Errorf("bad offset modulo: %d", b.offset)
1088 }
1089 if b.empty() {
1090 return fmt.Errorf("empty block")
1091 }
1092 if b.prev.next != b {
1093 return fmt.Errorf("bad prev.next link")
1094 }
1095 if b.next.prev != b {
1096 return fmt.Errorf("bad next.prev link")
1097 }
1098 if b.next == &s.root {
1099 break
1100 }
1101 if b.offset >= b.next.offset {
1102 return fmt.Errorf("bad offset order: b.offset=%d, b.next.offset=%d",
1103 b.offset, b.next.offset)
1104 }
1105 }
1106 return nil
1107 }