github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/tools/container/intsets/sparse.go (about)

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