CHAMP sets and maps

These changes complete the implementation of CHAMP sets and maps, which had been sitting around half-done for months. I have tested them on SBCL (2.5.3), CCL (1.13), CLASP (2.5.0), ABCL (1.9.2), ECL (24.5.10), Franz Allegro (11.0), and LispWorks (8.0.1).

CHAMP is Michael Steindorfer's evolution of Phil Bagwell's HAMT.

These are hash-based collections, in contrast to FSet's traditional WB-trees, which are ordering-based. They offer better time performance with usually slightly less space overhead, except on very small collections. The performance gain is especially notable in the "two-tree" algorithms like union and intersection; in one simple test, union was almost 4x faster.

So along with the existing compare generic function, there is now a generic function hash-value. If you want to use the new CHAMP collections with your own types, you need to either make sure methods exist for them on both compare and hash-value, or use custom comparison and hashing functions (see below). If you have been writing things like

(defmethod compare ((x frob) (y frob))
  fset:compare-slots x y 'size 'color))

then my recommendation is to change them to

(define-equality-slots frob 'size 'color)

The latter will define both compare and hash-value methods for you. If you have written more elaborate custom compare methods, you will need to work out how to write corresponding hash-value methods; see below.

CHAMP bags are not yet implemented, but I expect to get to them eventually.

To create a CHAMP set or map, you can call empty-ch-set or empty-ch-map, and then use repeated with to populate it, just as with the WB collections. Or, you can use the ch-set or ch-map constructor macro. (FSet still defaults to using the WB collections, in the sense that the functions/macros that don't specify an implementation — empty-set, empty-map, set, and map — still return the WB versions.) CHAMP collections print with an extra # at the beginning:

> (set 3)
#{ 3 }
> (ch-set 3)
##{ 3 }
> (map ('a 4))
#{| (A 4) |}
> (ch-map ('a 4))
##{| (A 4) |}

The iteration order of the CHAMP collections — which is evident in the order their elements are printed — is actually a deterministic function of the hash values of their contents, but that fact is of little use because the function is very complex and hard to describe. Don't expect the order to make sense.

CHAMP sets and maps implement almost the same API as their WB counterparts. Exceptions:

  • They don't support the least and greatest methods.
  • They don't support the "split" methods, split-from, split-above, split-through, and split-below.
  • There are no methods for rank and at-rank; instead there are the very similar methods index and at-index. The only difference is that given an element not in the collection, rank will return an index telling you where the element would go if it were added, but index will just return nil.

Writing hash functions

As mentioned above, the usual way to arrange for hashing of your own types is to use define-equality-slots, which will add methods to both hash-value and compare. However, if you have written a compare method yourself (e.g., for a non-FSet collection type), you will also want to write a corresponding hash-value method. Or, perhaps you want to use a custom comparison and hashing function (see below).

When hashing objects that can be large, such as collections, there are two general strategies for keeping the hashing time cost within reason. One is to bound the hash effort by simply stopping after some fixed number of hash steps. The other is to go ahead and hash the whole object, but then cache the hash value in a slot so that you don't have to do this more than once. FSet uses both approaches, depending on the type of collection.

For good performance, it is desirable to use fixnum arithmetic in the hashing functions. FSet provides two macros to help with this:

  • hash-mix combines hashes. It uses fixnum modular addition (that is, addition that discards overflow past the fixnum length) on most platforms; but on ABCL, CLASP, and ECL, I haven't figured out how to get the compiler to do that, so it uses XOR.
  • hash-mixf is the modify macro for hash-mix.
  • hash-multiply does fixnum modular multiplication.

Make sure that for any two objects on which compare returns :equal or :unequal, hash-value returns the same value.

Look in Code/hash.lisp for some examples.

Custom comparison and hashing functions

As with the WB collections, you can supply your own comparison and hashing functions. Doing so can improve performance by bypassing the overhead of CLOS generic functions compare and hash-value.

So as to present a similar interface as the WB collections, empty-ch-set and ch-custom-set accept a compare-fn-name, and empty-ch-map and ch-custom-map accept key-compare-fn-name and val-compare-fn-name. You should have associated a hash function with the compare function using define-hash-function (credit: this approach was inspired by SBCL's define-hash-table-test). FSet will then use that hash function when you specify that compare function. (Unlike with SBCL's hash tables, the hash function cannot be overridden at collection creation time.)

CHAMP maps need a compare and hash function for the (range) values as well as the keys. The value compare function is used similarly to the way it is used in WB maps: for determining when the range value for a key has actually been changed; for comparing two CH-maps, either just to see whether they're equal, or perhaps because they're nested in WB collections; and for the map-difference-2 operation. The value hash function is used to compute a hash value for the entire map, in the case where the map is nested inside another CHAMP or WB collection. That's a highly unusual thing to do, so I have arranged for the value hash function not to be called at all unless it is needed for that purpose.

For maps in which key hash collisions are expected to be very rare and the map is not going to be used as a set or bag element or as a key in another map, and when writing hash and compare functions for the values is onerous — or worse, impossible (e.g., for Lisp function objects) — I have provided compare function eql-compare, which returns :equal if its arguments are eql, otherwise :unequal. Its associated hash function is zero, which always returns 0.

Performance considerations

In the case of a hash collision — where two set/bag elements or map keys hash to the same value — the CHAMP collections fall back to using a WB collection for the collision set. This is potentially a great improvement over what most hash-based collections do, which is to do linear searches within collision sets. However, getting the benefit of it requires that the comparison function in use actually impose a suitable ordering and return :less or :greater when appropriate. A simple function like eql-compare that only ever returns :equal or :unequal doesn't impose an ordering; as a result, the WB collections will fall back a second time to using lists with linear searches. So if you're using eql-compare or a similar comparison function, it becomes more important to make sure that your hash function generates very few collisions.

However, if you're hashing large objects like long strings or large list structure trees, you can take considerable advantage of the WB fallback. There's a tension in hashing such objects: hashing the whole thing can be very expensive; but if you limit the number of elements hashed, you risk having more collisions, e.g. if your long strings tend to have common initial substrings. It's hard to know a priori just how much of the object you need to hash to get well-distributed hash values. But because of the WB fallback, you can often be fairly aggressive in cutting off the hashing process, risking some collisions, since the collision sets will still be handled pretty efficiently, as long as they don't get too big.

The other approach to minimizing the cost of hashing large objects is to go ahead and hash the whole thing, but then cache the result. FSet does this itself for the CHAMP collections.

Edited by Scott L. Burson

Merge request reports

Loading
+1776 −494
Changes for Code/champ.lisp: 1776 added lines, 494 removed lines.
Original line number Diff line number Diff line
@@ -13,11 +13,12 @@ (in-package :fset)
#||

Our implementation differs slightly from the published CHAMP algorithm.  It is agnostic as to the
number of bits in the hash values; it will use as many as are provided.  A collision can be detected
at any level, when two members/keys hash to the same value but `equal?' is false on them.  When that
happens, we fall back to using a WB-tree for those entries.  The resulting collision node will be as
high in the tree as possible given that it can contain only keys with that hash value; this can
require pushing it down an arbitrary number of levels when adding a new key.
number of bits in the hash values; it will use as many as are provided, up to the fixnum size.  A
collision can be detected at any level, when two members/keys hash to the same value but `equal?'
is false on them.  When that happens, we fall back to using a WB-tree for those entries.  The
resulting collision node will be as high in the tree as possible given that it can contain only
keys with that hash value; this can require pushing it down an arbitrary number of levels when
adding a new key.

As Steindorfer recommends, we do go to the trouble to canonicalize on deletion, so that the shape of
the tree is a function of the members/keys, i.e., is independent of how the tree was constructed.
@@ -29,20 +30,45 @@ (in-package :fset)
;;; ================================================================================
;;; Global constants

(defconstant champ-hash-bits-per-level 5)
;;; `eval-when' needed in Allegro to make the `deftype' work.
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defconstant champ-hash-bits-per-level
    ;; Drops to 4 on 32-bit implementations.
    (min 5 (- (integer-length (1+ (* 2 (integer-length most-positive-fixnum)))) 2)))
  (defconstant champ-node-radix (ash 1 champ-hash-bits-per-level))
(defconstant champ-hash-level-mask (1- champ-node-radix))
  (defconstant champ-hash-level-mask (1- champ-node-radix)))
(deftype champ-bit-index () `(integer 0 ,(1- champ-node-radix)))
;;; These have the same bounds but are logically different types.
(deftype champ-entry-index () `(integer 0 ,(1- champ-node-radix)))
(deftype champ-subnode-index () `(integer 0 ,(1- champ-node-radix)))

(declaim (inline champ-hash-bits)
	 (ftype (function (fixnum fixnum) champ-bit-index) champ-hash-bits))
(defun champ-hash-bits (hash depth)
  (ldb (byte champ-hash-bits-per-level (* depth champ-hash-bits-per-level))
       hash))

(declaim (inline 1-bits-below))
(defun 1-bits-below (idx mask)
  "The number of 1 bits in `mask' at bit positions (strictly) less than `idx'."
  (declare (optimize (speed 3))
	   (type champ-bit-index idx)
	   (fixnum mask))
  (logcount (logand (1- (the fixnum (ash 1 idx))) mask)))

(declaim (inline least-1-bit))
(defun least-1-bit (n)
  (declare (fixnum n))
  (1- (logcount (logxor n (1- n)))))

(defmacro do-bit-indices ((idx-var val &optional result) &body body)
  (let ((val-var (gensymx #:val-)))
    `(flet ((least-1-bit (n)
	      (1- (logcount (logxor n (1- n))))))
       (declare (inline least-1-bit))
       (let ((,val-var ,val))
    `(let ((,val-var ,val))
       (declare (fixnum ,val-var))
       (do ((,idx-var (least-1-bit ,val-var) (least-1-bit ,val-var)))
	   ((= 0 ,val-var) ,result)
	 (logandc2f ,val-var (ash 1 ,idx-var))
	  . ,body)))))
	. ,body))))

;;; Verification utility, used to recover hash bits from masks.
(defun bit-indices (mask)
@@ -52,35 +78,14 @@ (defun bit-indices (mask)
      (push i result))))


;;; Proclaiming a generic function to return a specific type doesn't stick -- at least on SBCL,
;;; recompiling a method removes the type.
(defun hash-value-fixnum (x)
  (let ((h (hash-value x)))
    (if (typep h 'fixnum)
	h
      ;; Anyway, using this wrapper lets us force the hash to be a fixnum.
      (let ((len (integer-length h))
	    (fixnum-len (integer-length most-positive-fixnum))
	    (fh 0))
	(dotimes (i (ceiling len fixnum-len))
	  (logxorf fh (ldb (byte fixnum-len (* fixnum-len i)) h)))
	fh))))
(declaim (ftype (function (t) fixnum) hash-value-fixnum))

;;; Although we tell people that the hash function must return a fixnum, we
;;; have no way to enforce that, so just to be sure, we check the return value.
;;; A fixnum test is pretty cheap on most platforms.
(defmacro hash-to-fixnum (val hash-fn)
  `(let ((h (funcall ,hash-fn ,val)))
     (if (typep h 'fixnum)
	 h
       (squash-bignum-hash h))))

(defun squash-bignum-hash (h)
  (let ((len (integer-length h))
	(fixnum-len (integer-length most-positive-fixnum))
	(fh 0))
    (dotimes (i (ceiling len fixnum-len))
      (logxorf fh (ldb (byte fixnum-len (* fixnum-len i)) h)))
    (if (< h 0) (- fh) fh)))
(declaim (ftype (function (t) fixnum) squash-bignum-hash))
       (the fixnum (squash-bignum-hash h)))))


;;; ================================================================================
@@ -92,26 +97,45 @@ (defstruct (ch-set-node
  ;; can't completely prevent a client from stupidly bashing them.
  (entry-mask 0 :type fixnum)
  (subnode-mask 0 :type fixnum)
  (size 0 :type integer) ; total number of elements at or below this node
  (size 0 :type fixnum) ; total number of elements at or below this node
  (hash-value 0 :type fixnum))
(defconstant ch-set-node-header-size 4)

(deftype ch-set-tree ()
  '(or null cons simple-vector))

(declaim (inline ch-set-tree-size))
(defun ch-set-tree-size (tree)
  (cond ((null tree) 0)
	((consp tree)
	 (wb-set-tree-size (cdr tree)))
	(t (ch-set-node-size tree))))

(declaim (inline ch-set-tree-hash-value))
(defun ch-set-tree-hash-value (tree)
  (cond ((null tree) 0)
	((consp tree) (the fixnum (car tree)))
	(t (ch-set-node-hash-value tree))))

(defun ch-set-tree-with (tree value hash-fn compare-fn &optional (depth 0))
  ;(declare (optimize (speed 3) (safety 0)))
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn)
	   (type (integer 0 64) depth))
  (let ((value-hash (hash-to-fixnum value hash-fn)))
    (declare (fixnum value-hash))
    (rlabels (rec tree (ash value-hash (- (* champ-hash-bits-per-level depth))) depth)
      (rec (node hash-shifted depth)
      (rec (node hash-shifted depth &optional node-hash)
	(declare (fixnum hash-shifted)
		 (type (integer 0 64) depth))
		 (type (integer 0 64) depth)
		 (type (or null fixnum) node-hash))
	(let ((hash-bits (logand hash-shifted champ-hash-level-mask)))
	  (if (null node)
	      (vector (ash 1 hash-bits) 0 1 value-hash value)
	    (if (consp node)
		;; We can create collision nodes at any level (see below).  -- Well, not at the root.  But
		;; this is called from elsewhere (e.g. `-union') on subtrees, which might be collision nodes.
		(let ((wb-hash-shifted (ash (hash-to-fixnum (wb-set-tree-arb (cdr node)) hash-fn)
					    (- (* champ-hash-bits-per-level depth))))
		(let ((node-hash (or node-hash (hash-to-fixnum (wb-set-tree-arb (cdr node)) hash-fn)))
		      ((wb-hash-shifted (ash node-hash (- (* champ-hash-bits-per-level depth)))))
		      (size (1+ (wb-set-tree-size (cdr node)))))
		  (declare (fixnum wb-hash-shifted hash-shifted size))
		  (if (= hash-shifted wb-hash-shifted)
@@ -120,27 +144,21 @@ (defun ch-set-tree-with (tree value hash-fn compare-fn &optional (depth 0))
			(if (eq new-wb-tree (cdr node))
			    node
			  ;; New entry in collision node
			  (cons (logxor (the fixnum (car node)) value-hash)
				new-wb-tree)))
		    ;; Oh, this is fun.  We add enough levels to get to where the hashes differ.
		    (rlabels (build hash-shifted wb-hash-shifted)
		      (build (hash-shifted wb-hash-shifted)
			(declare (fixnum hash-shifted wb-hash-shifted))
			  (cons (car node) new-wb-tree)))
		    (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
			  (wb-hash-bits (logand wb-hash-shifted champ-hash-level-mask))
			      (content-hash (logxor (the fixnum (car node)) value-hash)))
			  (content-hash (hash-mix (car node) value-hash)))
		      (if (= hash-bits wb-hash-bits)
			  (vector 0 (ash 1 hash-bits) size content-hash
				      (build (ash hash-shifted (- champ-hash-bits-per-level))
					     (ash wb-hash-shifted (- champ-hash-bits-per-level))))
				  (rec node (ash hash-shifted (- champ-hash-bits-per-level)) (1+ depth) node-hash))
			(vector (ash 1 hash-bits) (ash 1 wb-hash-bits) size content-hash
				    value node)))))))
				value node)))))
	      ;; Normal case
	      (let ((entry-mask (ch-set-node-entry-mask node))
		    ((entry-raw-idx (logcount (logand (1- (ash 1 hash-bits)) entry-mask)))
		    ((entry-raw-idx (1-bits-below hash-bits entry-mask))
		     ((entry-idx (+ ch-set-node-header-size entry-raw-idx))))
		    (subnode-mask (ch-set-node-subnode-mask node))
		    ((subnode-raw-idx (logcount (logand (1- (ash 1 hash-bits)) subnode-mask)))
		    ((subnode-raw-idx (1-bits-below hash-bits subnode-mask))
		     ((subnode-idx (- (the fixnum (length node)) 1 subnode-raw-idx)))))
		(declare (fixnum entry-mask entry-raw-idx entry-idx subnode-mask subnode-raw-idx subnode-idx))
		(if (logbitp hash-bits entry-mask)
@@ -154,10 +172,9 @@ (defun ch-set-tree-with (tree value hash-fn compare-fn &optional (depth 0))
			      ((ex-value-hash-shifted (ash ex-value-hash (* (- champ-hash-bits-per-level) (1+ depth))))
			       ((n2 (if (= hash-shifted ex-value-hash-shifted)
					;; Collision!  Fall back to WB-tree.
					(cons (logxor value-hash ex-value-hash)
					      (wb-set-tree-with (wb-set-tree-with nil ex-value compare-fn)
					(cons value-hash (wb-set-tree-with (wb-set-tree-with nil ex-value compare-fn)
									   value compare-fn))
				      ;; Creates a little garbage; &&& hand-integrate later.
				      ;; Turn the entry into a subnode and recur.
				      (rec (vector (ash 1 (logand ex-value-hash-shifted champ-hash-level-mask))
						   0 1 ex-value-hash ex-value)
					   hash-shifted (1+ depth))))
@@ -167,7 +184,8 @@ (defun ch-set-tree-with (tree value hash-fn compare-fn &optional (depth 0))
			  (logandc2f (ch-set-node-entry-mask n) (ash 1 hash-bits))
			  (logiorf (ch-set-node-subnode-mask n) (ash 1 hash-bits))
			  (incf (ch-set-node-size n))
			  (logxorf (ch-set-node-hash-value n) value-hash)
			  (unless (consp n2)
			    (hash-mixf (ch-set-node-hash-value n) value-hash))
			  n)))
		  ;; No entry found: check for subnode
		  (if (logbitp hash-bits subnode-mask)
@@ -181,18 +199,18 @@ (defun ch-set-tree-with (tree value hash-fn compare-fn &optional (depth 0))
			    (setf (ch-set-node-size n)
				  (the fixnum (+ (ch-set-node-size n) (- (the fixnum (ch-set-tree-size new-subnode))
									 (the fixnum (ch-set-tree-size subnode))))))
			    (logxorf (ch-set-node-hash-value n) (the fixnum (ch-set-tree-hash-value subnode))
				     (the fixnum (ch-set-tree-hash-value new-subnode)))
			    (hash-mixf (ch-set-node-hash-value n) (hash-unmix (ch-set-tree-hash-value new-subnode)
									      (ch-set-tree-hash-value subnode)))
			    n)))
		    ;; Neither entry nor subnode found: make new entry
		    (let ((n (vector-insert node entry-idx value)))
		      (logiorf (ch-set-node-entry-mask n) (ash 1 hash-bits))
		      (incf (ch-set-node-size n))
		      (logxorf (ch-set-node-hash-value n) value-hash)
		      (hash-mixf (ch-set-node-hash-value n) value-hash)
		      n)))))))))))

(defun vector-rem-1-ins-1 (vec rem-idx ins-idx ins-val)
  (declare ;(optimize (speed 3) (safety 0))
  (declare (optimize (speed 3) (safety 0))
	   (simple-vector vec)
	   (fixnum rem-idx ins-idx))
  (assert (<= rem-idx (the fixnum (1- ins-idx))))
@@ -210,82 +228,59 @@ (defun vector-rem-1-ins-1 (vec rem-idx ins-idx ins-val)
      (setf (svref v (+ ins-idx i)) (svref vec (+ ins-idx i))))
    v))

(defun ch-set-tree-size (tree)
  (cond ((null tree) 0)
	((consp tree)
	 (wb-set-tree-size (cdr tree)))
	(t (ch-set-node-size tree))))

(defun ch-set-tree-hash-value (tree)
  (cond ((null tree) 0)
	((consp tree) (car tree))
	(t (ch-set-node-hash-value tree))))

(defun ch-set-tree-less (tree value hash-fn compare-fn)
  ;(declare (optimize (speed 3) (safety 0)))
(defun ch-set-tree-less (tree value hash-fn compare-fn &optional (depth 0))
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn)
	   (type (integer 0 64) depth))
  (let ((value-hash (hash-to-fixnum value hash-fn)))
    (declare (fixnum value-hash))
    (rlabels (rec tree value-hash)
    (rlabels (rec tree (ash value-hash (- (* champ-hash-bits-per-level depth))))
      (rec (node hash-shifted)
	(declare (fixnum hash-shifted))
	(and node
	     (if (consp node)
		 (let ((new-wb-tree (wb-set-tree-less (cdr node) value compare-fn)))
		   (if (eq new-wb-tree (cdr node))
		       node
		     (if (= 1 (wb-set-tree-size new-wb-tree))
			 ;; Removing next-to-last entry of collision node: turn remaining value into entry
			 (let ((rem-val (wb-set-tree-arb new-wb-tree))
			       (hash-bits (logand hash-shifted champ-hash-level-mask)))
			   (vector (ash 1 hash-bits) 0 1 value-hash rem-val))
		       (cons (car node) new-wb-tree))))
	       (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
		     (entry-mask (ch-set-node-entry-mask node))
		   ((entry-raw-idx (logcount (logand (1- (ash 1 hash-bits)) entry-mask)))
		     ((entry-raw-idx (1-bits-below hash-bits entry-mask))
		      ((entry-idx (+ ch-set-node-header-size entry-raw-idx))))
		     (subnode-mask (ch-set-node-subnode-mask node)))
		 (if (logbitp hash-bits entry-mask)
		     (let ((ex-value (svref node entry-idx)))
		       (cond ((not (equal?-cmp ex-value value compare-fn))
			    (values node 0))
			      node)
			     ((and (= (logcount entry-mask) 1) (= 0 subnode-mask))
			    (values nil value-hash))
			      (assert (= depth 0))
			      nil)
			     (t
			      (let ((n (vector-remove-at node entry-idx)))
				(logandc2f (ch-set-node-entry-mask n) (ash 1 hash-bits))
				(decf (ch-set-node-size n))
			      (logxorf (ch-set-node-hash-value n) value-hash)
			      (values n value-hash)))))
		 (let ((subnode-raw-idx (logcount (logand (1- (ash 1 hash-bits)) subnode-mask)))
				(hash-unmixf (ch-set-node-hash-value n) value-hash)
				n))))
		   (let ((subnode-raw-idx (1-bits-below hash-bits subnode-mask))
			 ((subnode-idx (- (length node) 1 subnode-raw-idx))))
		     (if (not (logbitp hash-bits subnode-mask))
		       (values node 0)
		     (let ((subnode (svref node subnode-idx)))
		       (if (consp subnode)
			   (let ((new-wb-tree (wb-set-tree-less (cdr subnode) value #'compare)))
			     (if (eq new-wb-tree (cdr subnode))
				 (values node 0)
			       (if (= 1 (wb-set-tree-size new-wb-tree))
				   ;; Removing next-to-last entry of collision node: turn remaining value into entry
				   (let ((rem-val (wb-set-tree-arb new-wb-tree))
					 ;; `entry-idx' is still valid from above; the hash bits must be the same
					 ((n (vector-ins-1-rem-1 node entry-idx rem-val subnode-idx))))
				     (logiorf (ch-set-node-entry-mask n) (ash 1 hash-bits))
				     (logandc2f (ch-set-node-subnode-mask n) (ash 1 hash-bits))
				     (decf (ch-set-node-size n))
				     (logxorf (ch-set-node-hash-value n) value-hash)
				     (values n value-hash))
				 (let ((n (vector-update node subnode-idx
							 (cons (logxor (the fixnum (car subnode)) value-hash)
							       new-wb-tree))))
				   (decf (ch-set-node-size n))
				   (logxorf (ch-set-node-hash-value n) value-hash)
				   (values n value-hash)))))
			 (let ((new-subnode content-hash-delta
				 (rec subnode (ash hash-shifted (- champ-hash-bits-per-level)))))
			   (declare (fixnum content-hash-delta))
			 node
		       (let ((subnode (svref node subnode-idx))
			     ((new-subnode (rec subnode (ash hash-shifted (- champ-hash-bits-per-level))))))
			 (if (eq new-subnode subnode)
			       (values node 0)
			     (let ((n (cond ((null new-subnode)
					     (let ((n (vector-remove-at node subnode-idx)))
					       (logandc2f (ch-set-node-subnode-mask n) (ash 1 hash-bits))
					       n))
			     node
			   (let ((n (cond ((consp new-subnode)
					   (vector-update node subnode-idx new-subnode))
					  ((and (= 1 (logcount (ch-set-node-entry-mask new-subnode)))
						(= 0 (ch-set-node-subnode-mask new-subnode)))
					   ;; New subnode contains only a single entry: pull it up into this node
					   (let ((new-entry-idx
						     (+ ch-set-node-header-size
							(logcount (logand (1- (ash 1 hash-bits)) entry-mask))))
						   (+ ch-set-node-header-size (1-bits-below hash-bits entry-mask)))
						 ((n (vector-ins-1-rem-1 node new-entry-idx
									 (svref new-subnode ch-set-node-header-size)
									 subnode-idx))))
@@ -300,11 +295,12 @@ (defun ch-set-tree-less (tree value hash-fn compare-fn)
							  (svref new-subnode ch-set-node-header-size)))
					  (t (vector-update node subnode-idx new-subnode)))))
			     (decf (ch-set-node-size n))
			       (logxorf (ch-set-node-hash-value n) content-hash-delta)
			       (values n content-hash-delta)))))))))))))))
			     (hash-mixf (ch-set-node-hash-value n) (hash-unmix (ch-set-tree-hash-value new-subnode)
									       (ch-set-tree-hash-value subnode)))
			     n)))))))))))))

(defun vector-ins-1-rem-1 (vec ins-idx ins-val rem-idx)
  (declare ;(optimize (speed 3) (safety 0))
  (declare (optimize (speed 3) (safety 0))
	   (simple-vector vec)
	   (fixnum ins-idx rem-idx))
  (assert (<= ins-idx rem-idx))
@@ -320,6 +316,7 @@ (defun vector-ins-1-rem-1 (vec ins-idx ins-val rem-idx)
    v))

(defun ch-set-tree-arb (tree)
  (declare (optimize (speed 3) (safety 0)))
  (cond ((null tree)
	 (error "'ch-set-tree-arb' called on empty tree"))
	((consp tree)
@@ -331,7 +328,9 @@ (defun ch-set-tree-arb (tree)
	 (svref tree ch-set-node-header-size))))

(defun ch-set-tree-contains? (tree value hash-fn compare-fn &optional (depth 0))
  ;(declare (optimize (speed 3) (safety 0)))
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn)
	   (type (integer 0 64) depth))
  (let ((value-hash (hash-to-fixnum value hash-fn)))
    (declare (fixnum value-hash))
    (rlabels (rec tree value (ash value-hash (- (* champ-hash-bits-per-level depth))))
@@ -339,22 +338,23 @@ (defun ch-set-tree-contains? (tree value hash-fn compare-fn &optional (depth 0))
	(declare (fixnum hash-shifted))
	(and node
	     (if (consp node)
		 (wb-set-tree-member? (cdr node) value compare-fn)
		 (wb-set-tree-find-equal (cdr node) value compare-fn)
	       (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
		     (entry-mask (ch-set-node-entry-mask node)))
		 (if (logbitp hash-bits entry-mask)
		     (let ((entry-idx (+ ch-set-node-header-size
					 (logcount (logand (1- (ash 1 hash-bits)) entry-mask))))
		     (let ((entry-idx (+ ch-set-node-header-size (1-bits-below hash-bits entry-mask)))
			   ((ex-value (svref node entry-idx))))
		       (equal?-cmp ex-value value compare-fn))
		       (and (equal?-cmp ex-value value compare-fn)
			    (values t ex-value)))
		   (let ((subnode-mask (ch-set-node-subnode-mask node)))
		     (and (logbitp hash-bits subnode-mask)
			  (let ((subnode-idx (- (length node) 1
						(logcount (logand (1- (ash 1 hash-bits)) subnode-mask))))
			  (let ((subnode-idx (- (length node) 1 (1-bits-below hash-bits subnode-mask)))
				((subnode (svref node subnode-idx))))
			    (rec subnode value (ash hash-shifted (- champ-hash-bits-per-level))))))))))))))

(defun ch-set-tree-compare (tree1 tree2 compare-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function compare-fn))
  (if (eq tree1 tree2) ':equal
    (let ((size1 (ch-set-tree-size tree1))
	  (size2 (ch-set-tree-size tree2)))
@@ -367,7 +367,7 @@ (defun ch-set-tree-compare (tree1 tree2 compare-fn)
	       (cond ((< hash1 hash2) ':less)
		     ((> hash1 hash2) ':greater)
		     ((consp tree1)
		      (if (consp tree2) (wb-set-tree-compare (cdr tree1) (cdr tree2) #'compare)
		      (if (consp tree2) (wb-set-tree-compare (cdr tree1) (cdr tree2) compare-fn)
			':less))
		     ((consp tree2) ':greater)
		     (t
@@ -405,50 +405,329 @@ (defun ch-set-tree-compare (tree1 tree2 compare-fn)
					 (return-from ch-set-tree-compare cmp)))))
				 default))))))))))))

(defun ch-set-tree-index (tree value hash-fn compare-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn))
  (let ((value-hash (hash-to-fixnum value hash-fn)))
    (declare (fixnum value-hash))
    (rlabels (rec tree value 0 value-hash)
      (rec (node value base hash-shifted)
	(declare (fixnum base hash-shifted))
	(and node
	     (if (consp node)
		 (let ((found? idx (wb-set-tree-rank (cdr node) value compare-fn)))
		   (and found? (the fixnum (+ (the fixnum idx) base))))
	       (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
		     (entry-mask (ch-set-node-entry-mask node)))
		 (if (logbitp hash-bits entry-mask)
		     (let ((ientry (1-bits-below hash-bits entry-mask))
			   ((entry-idx (+ ch-set-node-header-size ientry))
			    ((ex-value (svref node entry-idx)))))
		       (and (equal?-cmp ex-value value compare-fn)
			    (the fixnum (+ base ientry))))
		   (let ((subnode-mask (ch-set-node-subnode-mask node)))
		     (incf base (logcount entry-mask))
		     (and (logbitp hash-bits subnode-mask)
			  (let ((isubnode (1-bits-below hash-bits subnode-mask))
				(len (length (the simple-vector node)))
				((subnode-idx (- len 1 isubnode))
				 ((subnode (svref node subnode-idx)))))
			    (dotimes (i isubnode)
			      (incf base (ch-set-tree-size (svref node (- len 1 i)))))
			    (rec subnode value base
				 (ash hash-shifted (- champ-hash-bits-per-level))))))))))))))

(defun ch-set-tree-index-element (tree index)
  (declare (optimize (debug 3)))
  (declare (optimize (speed 3) (safety 0)))
  (rlabels (rec tree index)
    (rec (tree index)
      (declare (fixnum index))
      (if (consp tree)
	  (wb-set-tree-rank-element (cdr tree) index)
	(let ((len (length tree))
	(let ((len (length (the simple-vector tree)))
	      (entry-mask (ch-set-node-entry-mask tree))
	      (subnode-mask (ch-set-node-subnode-mask tree))
	      ((merged-mask (logior entry-mask subnode-mask)))
	      (entry-idx 0)
	      (subnode-idx 0))
	  (do-bit-indices (idx merged-mask (error "'Bug in ch-set-tree-index-element'"))
	    (cond ((logbitp idx entry-mask)
		   (when (= index 0)
		     (return (svref tree (+ ch-set-node-header-size entry-idx))))
		   (decf index)
		   (incf entry-idx))
		  ((logbitp idx subnode-mask)
		   (let ((subnode (svref tree (- len subnode-idx 1)))
	      ((n-entries (logcount entry-mask))))
	  (if (< index n-entries)
	      (svref tree (+ ch-set-node-header-size index))
	    (let ((subnode-mask (ch-set-node-subnode-mask tree)))
	      (decf index n-entries)
	      (dotimes (i (logcount subnode-mask))
		(let ((subnode (svref tree (- len i 1)))
		      ((subnode-size (ch-set-tree-size subnode))))
		  (when (< index subnode-size)
		    (return (rec subnode index)))
		     (decf index subnode-size)
		     (incf subnode-idx))))))))))
		  (decf index subnode-size))))))))))

(defun vector-remove-n-at (vec idx n)
  (declare (optimize (speed 3) (safety 0))
	   (type simple-vector vec)
	   (type (unsigned-byte 24) idx n))
  (let ((len (length vec)))
    (declare (type fixnum len))
    (let ((new-vec (make-array (- len n))))
      (dotimes (i idx)
	(setf (svref new-vec i) (svref vec i)))
      (dotimes (i (- len idx n))
	(setf (svref new-vec (+ idx i)) (svref vec (+ idx i n))))
      new-vec)))


;;; --------------------------------
;;; Iteration primitives

;;; This ordering has the slight downside that it can seem unstable; adding or removing an element
;;; can cause a different element to change places (because an entry becomes a subnode or conversely).
;;; But doing it hash-wise is noticeably slower, like a factor of 2 on a straightforward micro-benchmark.
;;; And one of the selling points of CHAMP was supposed to be its better iteration performance.
(defmacro do-ch-set-tree-members ((value-var tree-form &optional value-form)
				  &body body)
  (let ((body-fn (gensymx #:body-))
	(recur-fn (gensymx #:recur-)))
    `(block nil
       (labels ((,body-fn (,value-var)
		  . ,body)
		(,recur-fn (tree)
		  (when tree
		    (if (consp tree)
			(do-wb-set-tree-members (,value-var (cdr tree))
			  (,body-fn ,value-var))
		      (progn
			(dotimes (i (logcount (ch-set-node-entry-mask tree)))
			  (,body-fn (svref tree (+ i ch-set-node-header-size))))
			(dotimes (i (logcount (ch-set-node-subnode-mask tree)))
			  (,recur-fn (svref tree (- (length tree) 1 i)))))))))
	 (declare (inline ,body-fn))
	 (,recur-fn ,tree-form))
       ,value-form)))

;;; ----------------
;;; Stateful iterator

(defun make-ch-set-tree-iterator (tree)
  (let ((iter (make-ch-set-tree-iterator-internal tree)))
    (lambda (op)
      (ecase op
	(:get (ch-set-tree-iterator-get iter))
	(:done? (ch-set-tree-iterator-done? iter))
	(:more? (not (ch-set-tree-iterator-done? iter)))))))

(defun make-ch-set-tree-iterator-internal (tree)
  (declare (optimize (speed 3) (safety 0)))
  ;; Unlike with the WB-trees, the maximum depth here is not a function of the set size.
  (let ((iter (make-array (+ 1 (* 2 (ceiling (integer-length most-positive-fixnum) champ-hash-bits-per-level))))))
    (if (null tree)
	(setf (svref iter 0) -1)
      (progn
	(setf (svref iter 0) 1) ; the stack pointer
	(setf (svref iter 1) tree)
	(setf (svref iter 2) 0)
	(ch-set-tree-iterator-canonicalize iter)))
    iter))

(defun ch-set-tree-iterator-canonicalize (iter)
  (declare (optimize (speed 3) (safety 0)))
  (let ((sp (svref iter 0))
	((node (svref iter sp))
	 (idx (svref iter (1+ sp)))))
    (declare (type (or null fixnum) idx))
    (when (if (null idx)
	      (wb-set-tree-iterator-done? (svref iter sp))
	    (= idx (- (length (the simple-vector node)) ch-set-node-header-size)))
      (decf sp 2)
      (unless (< sp 0)
	(setq node (svref iter sp))
	(setq idx (svref iter (1+ sp)))))
    (unless (< sp 0)
      (loop
	(when (null idx)
	  (return))
	(let ((n-entries (logcount (ch-set-node-entry-mask node))))
	  (when (< idx n-entries)
	    (return))
	  (let ((len (length (the simple-vector node))))
	    (setq node (svref node (- len (- idx n-entries) 1)))
	    (incf idx)
	    (unless (= idx (- len ch-set-node-header-size)) ; TCO
	      (setf (svref iter (1+ sp)) idx)
	      (incf sp 2))
	    (if (consp node)
		(setq node (make-wb-set-tree-iterator-internal (cdr node))
		      idx nil)
	      (setq idx 0))
	    (setf (svref iter sp) node)
	    (setf (svref iter (1+ sp)) idx)))))
    (setf (svref iter 0) sp)))

(defun ch-set-tree-iterator-done? (iter)
  (declare (optimize (speed 3) (safety 0)))
  (< (the fixnum (svref iter 0)) 0))

(defun ch-set-tree-iterator-get (iter)
  (declare (optimize (speed 3) (safety 0)))
  (let ((sp (svref iter 0)))
    (declare (fixnum sp))
    (and (> sp 0)
	 (let ((node (svref iter sp))
	       (idx (svref iter (1+ sp))))
	   (declare (type (or null fixnum) idx))
	   (if (null idx)
	       (let ((val (wb-set-tree-iterator-get node)))
		 (ch-set-tree-iterator-canonicalize iter)
		 (values val t))
	     (progn
	       (setf (svref iter (1+ sp)) (1+ idx))
	       (ch-set-tree-iterator-canonicalize iter)
	       (values (svref node (+ ch-set-node-header-size idx))
		       t)))))))

;;; ----------------
;;; Functional iterator

(defun ch-set-tree-fun-iter (tree)
  (declare (optimize (speed 3) (safety 0)))
  (rlabels (walk tree (lambda (op)
			(ecase op
			  (:first (values nil nil))
			  (:empty? t)
			  (:more? nil))))
    (walk (node cont)
      (if (consp node)
	  (wb-set-tree-fun-iter (cdr node) cont)
	(let ((n-entries (logcount (ch-set-node-entry-mask node)))
	      (n-subnodes (logcount (ch-set-node-subnode-mask node))))
	  (rlabels (entry 0)
	    (entry (i)
	      (declare (fixnum i))
	      (if (< i n-entries)
		  (lambda (op)
		    (ecase op
		      (:first (values (svref node (+ ch-set-node-header-size i)) t))
		      (:rest (entry (1+ i)))
		      (:empty? nil)
		      (:more? t)))
		(subnode 0)))
	    (subnode (i)
	      (declare (fixnum i))
	      (if (< i n-subnodes)
		  (walk (svref node (- (+ ch-set-node-header-size n-entries n-subnodes)
				       i 1))
			(lambda (op) (funcall (the function (subnode (1+ i))) op)))
		cont))))))))

(defun ch-set-tree-rev-fun-iter (tree)
  (declare (optimize (speed 3) (safety 0)))
  (rlabels (walk tree (lambda (op)
			(ecase op
			  (:first (values nil nil))
			  (:empty? t)
			  (:more? nil))))
    (walk (node cont)
      (if (consp node)
	  (wb-set-tree-rev-fun-iter (cdr node) cont)
	(let ((n-entries (logcount (ch-set-node-entry-mask node)))
	      (n-subnodes (logcount (ch-set-node-subnode-mask node))))
	  (rlabels (subnode (1- n-subnodes))
	    (entry (i)
	      (declare (fixnum i))
	      (if (>= i 0)
		  (lambda (op)
		    (ecase op
		      (:first (values (svref node (+ ch-set-node-header-size i)) t))
		      (:rest (entry (1- i)))
		      (:empty? nil)
		      (:more? t)))
		cont))
	    (subnode (i)
	      (declare (fixnum i))
	      (if (>= i 0)
		  (walk (svref node (- (+ ch-set-node-header-size n-entries n-subnodes)
				       i 1))
			(lambda (op) (funcall (the function (subnode (1- i))) op)))
		(entry (1- n-entries))))))))))


;;; --------------------------------
;;; Union, intersection, set-difference, subset?, disjoint?

(declaim (inline ch-set-node-entry))
(defun ch-set-node-entry (n ientry)
  (declare (optimize (speed 3) (safety 0))
	   (type simple-vector n)
	   (type champ-entry-index ientry))
  (svref n (+ ch-set-node-header-size ientry)))

(declaim (inline ch-set-node-subnode))
(defun ch-set-node-subnode (n isubnode)
  (declare (optimize (speed 3) (safety 0))
	   (type simple-vector n)
	   (type champ-subnode-index isubnode))
  (svref n (- (length n) isubnode 1)))

(declaim (inline ch-set-node-add-entry))
(defun ch-set-node-add-entry (n idx val hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type champ-bit-index idx)
	   (type function hash-fn))
  (setf (svref n (+ ch-set-node-header-size (logcount (ch-set-node-entry-mask n)))) val)
  (logiorf (ch-set-node-entry-mask n) (ash 1 idx))
  (incf (ch-set-node-size n))
  (hash-mixf (ch-set-node-hash-value n) (hash-to-fixnum val hash-fn)))

(declaim (inline ch-set-node-add-subnode))
(defun ch-set-node-add-subnode (n idx subnode hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type champ-bit-index idx)
	   (type function hash-fn))
  (when subnode
    (if (and (not (consp subnode))
	     (= 1 (logcount (ch-set-node-entry-mask subnode)))
	     (= 0 (ch-set-node-subnode-mask subnode)))
	;; `subnode' contains only an entry -- pull it up.
	(ch-set-node-add-entry n idx (svref subnode ch-set-node-header-size) hash-fn)
      (progn
	(when (and (not (consp subnode))
		   (= 0 (ch-set-node-entry-mask subnode))
		   (= 1 (logcount (ch-set-node-subnode-mask subnode)))
		   (consp (svref subnode (1- (length subnode)))))
	  ;; `subnode' contains only a collision subnode -- pull it up.
	  (setq subnode (svref subnode (1- (length subnode)))))
	(setf (svref n (- (length (the simple-vector n))
			  (logcount (ch-set-node-subnode-mask n)) 1))
	      subnode)
	(logiorf (ch-set-node-subnode-mask n) (ash 1 idx))
	(incf (ch-set-node-size n) (ch-set-tree-size subnode))
	(hash-mixf (ch-set-node-hash-value n) (ch-set-tree-hash-value subnode))))))

(defun ch-set-tree-union (tree1 tree2 hash-fn compare-fn)
  (declare (optimize (debug 3)))
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn))
  (rlabels (rec tree1 tree2 0)
    (rec (tree1 tree2 depth)
      (declare (type (integer 0 64) depth))
      (cond ((null tree1) tree2)
	    ((null tree2) tree1)
	    ((eq tree1 tree2) tree1)
	    ((and (consp tree1) (consp tree2))
	     (let ((tree-result (wb-set-tree-union (cdr tree1) (cdr tree2) compare-fn))
		   (chash 0))
	       (do-wb-set-tree-members (v tree-result)
		 (logxorf chash (hash-to-fixnum v hash-fn)))
	       (cons chash tree-result)))
	    ((or (consp tree1) (consp tree2))
	     (let ((collision-node normal-node (if (consp tree1) (values tree1 tree2) (values tree2 tree1))))
	       ;; Garbagey, but nontrivial to improve on, AFAICS.
	       (do-wb-set-tree-members (x (cdr collision-node))
		 (setq normal-node (ch-set-tree-with normal-node x hash-fn compare-fn depth)))
	       normal-node))
	     (let ((hash1 (the fixnum (car tree1)))
		   (hash2 (the fixnum (car tree2))))
	       (if (= hash1 hash2)
		   (let ((result (wb-set-tree-union (cdr tree1) (cdr tree2) compare-fn)))
		     (ch-set-node-from-wb result hash1 depth))
		 (let ((size (+ (wb-set-tree-size (cdr tree1)) (wb-set-tree-size (cdr tree2))))
		       (bits1 (champ-hash-bits hash1 depth))
		       (bits2 (champ-hash-bits hash2 depth))
		       (chash (hash-mix (car tree1) (car tree2))))
		   (declare (fixnum size))
		   (if (= bits1 bits2)
		       (vector 0 (ash 1 bits1) size chash (rec tree1 tree2 (1+ depth)))
		     (let ((subnode0 subnode1 (swap-if (> bits1 bits2) tree1 tree2)))
		       (vector 0 (logior (ash 1 bits1) (ash 1 bits2)) size chash subnode1 subnode0)))))))
	    ((consp tree1)
	     (do-wb-set-tree-members (x (cdr tree1))
	       (setq tree2 (ch-set-tree-with tree2 x hash-fn compare-fn depth)))
	     tree2)
	    ((consp tree2)
	     (rec tree2 tree1 depth))
	    (t
	     (let ((entries1 (ch-set-node-entry-mask tree1))
		   (entries2 (ch-set-node-entry-mask tree2))
@@ -456,96 +735,72 @@ (defun ch-set-tree-union (tree1 tree2 hash-fn compare-fn)
		   (subnodes2 (ch-set-node-subnode-mask tree2))
		   ((all-entries (logior entries1 entries2))
		    (all-subnodes (logior subnodes1 subnodes2))
		    ((everything (logior all-entries all-subnodes))
		    ;; Entry collisions can change to subnodes, but they can't then collide with existing subnodes.
		    ;; But we do have to subtract out entry/subnode collisions.
		    ((new-len (- (+ ch-set-node-header-size (logcount all-entries) (logcount all-subnodes))
				 (logcount (logand entries1 subnodes2)) (logcount (logand entries2 subnodes1))))
		      ((n (make-array new-len))))))
		     ((res-n (make-array new-len :initial-element 0)))))
		   (ientry1 0)
		   (isubnode1 0)
		   (ientry2 0)
		   (isubnode2 0)
		   ;; About the result...
		   (entries 0)
		   (subnodes 0)
		   (ientry 0)
		   (isubnode 0)
		   (size 0)
		   (content-hash 0))
		   (isubnode2 0))
	       (declare (fixnum ientry1 isubnode1 ientry2 isubnode2))
	       (flet ((add-entry (idx val)
			(setf (svref n (+ ch-set-node-header-size (postincf ientry))) val)
			(logiorf entries (ash 1 idx))
			(incf size)
			(logxorf content-hash (hash-to-fixnum val hash-fn)))
			(ch-set-node-add-entry res-n idx val hash-fn))
		      (add-subnode (idx subnode)
			;; It's possible for `subnode' to contain only a collision subnode -- we must pull it up.
			(when (and (not (consp subnode))
				   (= 0 (ch-set-node-entry-mask subnode))
				   (= 1 (logcount (ch-set-node-subnode-mask subnode)))
				   (consp (svref subnode (1- (length subnode)))))
			  (setq subnode (svref subnode (1- (length subnode)))))
			(setf (svref n (- new-len (postincf isubnode) 1)) subnode)
			(logiorf subnodes (ash 1 idx))
			(incf size (ch-set-tree-size subnode))
			(logxorf content-hash (ch-set-tree-hash-value subnode)))
		      (set-tree-with (tree value depth)
			(ch-set-tree-with tree value hash-fn compare-fn depth)))
		 (do-bit-indices (idx everything)
			(ch-set-node-add-subnode res-n idx subnode hash-fn))
		      (subtree-with (tree value)
			(ch-set-tree-with tree value hash-fn compare-fn (1+ depth))))
		 (do-bit-indices (idx (logior all-entries all-subnodes))
		   (cond ((and (logbitp idx entries1) (logbitp idx entries2))
			  (let ((val1 (svref tree1 (+ ch-set-node-header-size (postincf ientry1))))
				(val2 (svref tree2 (+ ch-set-node-header-size (postincf ientry2)))))
			  (let ((val1 (ch-set-node-entry tree1 (postincf ientry1)))
				(val2 (ch-set-node-entry tree2 (postincf ientry2))))
			    (if (equal?-cmp val1 val2 compare-fn)
				(add-entry idx val1)
			      (add-subnode idx (set-tree-with (set-tree-with nil val1 (1+ depth))
							      val2 (1+ depth))))))
			      (add-subnode idx (subtree-with (subtree-with nil val1) val2)))))
			 ((logbitp idx entries1)
			  (let ((val (svref tree1 (+ ch-set-node-header-size (postincf ientry1)))))
			  (let ((val (ch-set-node-entry tree1 (postincf ientry1))))
			    (if (logbitp idx subnodes2)
				(let ((subnode (svref tree2 (- (length tree2) (postincf isubnode2) 1))))
				  (add-subnode idx (set-tree-with subnode val (1+ depth))))
				(let ((subnode (ch-set-node-subnode tree2 (postincf isubnode2))))
				  (add-subnode idx (subtree-with subnode val)))
			      (add-entry idx val))))
			 ((logbitp idx entries2)
			  (let ((val (svref tree2 (+ ch-set-node-header-size (postincf ientry2)))))
			  (let ((val (ch-set-node-entry tree2 (postincf ientry2))))
			    (if (logbitp idx subnodes1)
				(let ((subnode (svref tree1 (- (length tree1) (postincf isubnode1) 1))))
				  (add-subnode idx (set-tree-with subnode val (1+ depth))))
				(let ((subnode (ch-set-node-subnode tree1 (postincf isubnode1))))
				  (add-subnode idx (subtree-with subnode val)))
			      (add-entry idx val))))
			 ((and (logbitp idx subnodes1) (logbitp idx subnodes2))
			  (add-subnode idx (rec (svref tree1 (- (length tree1) (postincf isubnode1) 1))
						(svref tree2 (- (length tree2) (postincf isubnode2) 1))
			  (add-subnode idx (rec (ch-set-node-subnode tree1 (postincf isubnode1))
						(ch-set-node-subnode tree2 (postincf isubnode2))
						(1+ depth))))
			 ((logbitp idx subnodes1)
			  (add-subnode idx (svref tree1 (- (length tree1) (postincf isubnode1) 1))))
			  (add-subnode idx (ch-set-node-subnode tree1 (postincf isubnode1))))
			 ((logbitp idx subnodes2)
			  (add-subnode idx (svref tree2 (- (length tree2) (postincf isubnode2) 1))))
			  (add-subnode idx (ch-set-node-subnode tree2 (postincf isubnode2))))
			 (t (error "Bug in 'ch-set-tree-union'")))))
	       (assert (= new-len (+ ch-set-node-header-size ientry isubnode)))
	       (setf (ch-set-node-entry-mask n) entries)
	       (setf (ch-set-node-subnode-mask n) subnodes)
	       (setf (ch-set-node-size n) size)
	       (setf (ch-set-node-hash-value n) content-hash)
	       n))))))
	       res-n))))))

(defun ch-set-tree-intersection (tree1 tree2 hash-fn compare-fn)
  (declare (optimize (debug 3)))
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn))
  (rlabels (rec tree1 tree2 0)
    (rec (tree1 tree2 depth)
      (declare (type (integer 0 64) depth))
      (cond ((or (null tree1) (null tree2)) nil)
	    ((and (consp tree1) (consp tree2))
	     (let ((tree-result (wb-set-tree-intersect (cdr tree1) (cdr tree2) compare-fn))
		   (chash 0))
	       (do-wb-set-tree-members (v tree-result)
		 (logxorf chash (hash-to-fixnum v hash-fn)))
	       (cons chash tree-result)))
	    ((or (consp tree1) (consp tree2))
	     (let ((collision-node normal-node (if (consp tree1) (values tree1 tree2) (values tree2 tree1)))
		   (result nil))
	       ;; Garbagey, but nontrivial to improve on, AFAICS.
	       (do-wb-set-tree-members (x (cdr collision-node))
		 (when (ch-set-tree-contains? normal-node x hash-fn compare-fn depth)
	    ((eq tree1 tree2) tree1)
	    ((consp tree1)
	     (if (consp tree2)
		 (and (= (the fixnum (car tree1)) (the fixnum (car tree2)))
		      (let ((result (wb-set-tree-intersect (cdr tree1) (cdr tree2) compare-fn)))
			(ch-set-node-from-wb result (car tree1) depth)))
	       (let ((result nil))
		 (do-wb-set-tree-members (x (cdr tree1))
		   (when (ch-set-tree-contains? tree2 x hash-fn compare-fn depth)
		     (setq result (ch-set-tree-with result x hash-fn compare-fn depth))))
	       result))
		 result)))
	    ((consp tree2)
	     (rec tree2 tree1 depth))
	    (t
	     (let ((entries1 (ch-set-node-entry-mask tree1))
		   (entries2 (ch-set-node-entry-mask tree2))
@@ -553,157 +808,308 @@ (defun ch-set-tree-intersection (tree1 tree2 hash-fn compare-fn)
		   (subnodes2 (ch-set-node-subnode-mask tree2))
		   ;; Unlike in the union case, where we can compute the size in advance, for the intersection
		   ;; we can only compute an upper bound -- the result could even be empty.
		   ((new-len (min (length tree1) (length tree2)))
		    ((n (make-array new-len))))
		   ;; About the result...
		   (entries 0)
		   (subnodes 0)
		   (ientry 0)
		   (isubnode 0)
		   (size 0)
		   (content-hash 0))
	       (labels ((add-entry (idx val)
			  (setf (svref n (+ ch-set-node-header-size (postincf ientry))) val)
			  (logiorf entries (ash 1 idx))
			  (incf size)
			  (logxorf content-hash (hash-to-fixnum val hash-fn)))
		   ((res-len (min (length tree1) (length tree2)))
		    ((res-n (make-array res-len :initial-element 0)))))
	       (flet ((add-entry (idx val)
			(ch-set-node-add-entry res-n idx val hash-fn))
		      (add-subnode (idx subnode)
			  (when subnode
			    (if (and (not (consp subnode))
				     (= 1 (logcount (ch-set-node-entry-mask subnode)))
				     (= 0 (ch-set-node-subnode-mask subnode)))
				;; `subnode' contains only an entry -- pull it up.
				(add-entry idx (svref subnode ch-set-node-header-size))
			      (progn
				;; `subnode' contains only a collision subnode -- pull it up.
				(when (and (not (consp subnode))
					   (= 0 (ch-set-node-entry-mask subnode))
					   (= 1 (logcount (ch-set-node-subnode-mask subnode)))
					   (consp (svref subnode (1- (length subnode)))))
				  (setq subnode (svref subnode (1- (length subnode)))))
				(setf (svref n (- new-len (postincf isubnode) 1)) subnode)
				(logiorf subnodes (ash 1 idx))
				(incf size (ch-set-tree-size subnode))
				(logxorf content-hash (ch-set-tree-hash-value subnode))))))
			;; The trick we used in `union' of just incrementing indices doesn't work here.
			(bits-below (idx mask)
			  (logcount (logand (1- (ash 1 idx)) mask))))
			(ch-set-node-add-subnode res-n idx subnode hash-fn))
		      (subtree-contains? (tree val)
			(ch-set-tree-contains? tree val hash-fn compare-fn (1+ depth))))
		 (do-bit-indices (idx (logior (logand entries1 entries2) (logand subnodes1 subnodes2)
					      (logand entries1 subnodes2) (logand subnodes1 entries2)))
		   ;; Here and in the other algorithms that don't look at every bit in the OR of
		   ;; the masks, we have to use `1-bits-below' instead of counters to get the indices.
		   (cond ((and (logbitp idx entries1) (logbitp idx entries2))
			  (let ((val1 (svref tree1 (+ ch-set-node-header-size (bits-below idx entries1))))
				(val2 (svref tree2 (+ ch-set-node-header-size (bits-below idx entries2)))))
			  (let ((val1 (ch-set-node-entry tree1 (1-bits-below idx entries1)))
				(val2 (ch-set-node-entry tree2 (1-bits-below idx entries2))))
			    (when (equal?-cmp val1 val2 compare-fn)
			      (add-entry idx val1))))
			 ((and (logbitp idx entries1) (logbitp idx subnodes2))
			  (let ((val (svref tree1 (+ ch-set-node-header-size (bits-below idx entries1)))))
			    (when (ch-set-tree-contains? (svref tree2 (- (length tree2) (bits-below idx subnodes2) 1))
							 val hash-fn compare-fn (1+ depth))
			  (let ((val (ch-set-node-entry tree1 (1-bits-below idx entries1))))
			    (when (subtree-contains? (ch-set-node-subnode tree2 (1-bits-below idx subnodes2)) val)
			      (add-entry idx val))))
			 ((and (logbitp idx subnodes1) (logbitp idx entries2))
			  (let ((val (svref tree2 (+ ch-set-node-header-size (bits-below idx entries2)))))
			    (when (ch-set-tree-contains? (svref tree1 (- (length tree1) (bits-below idx subnodes1) 1))
							 val hash-fn compare-fn (1+ depth))
			  (let ((val (ch-set-node-entry tree2 (1-bits-below idx entries2))))
			    (when (subtree-contains? (ch-set-node-subnode tree1 (1-bits-below idx subnodes1)) val)
			      (add-entry idx val))))
			 ((and (logbitp idx subnodes1) (logbitp idx subnodes2))
			  (add-subnode idx (rec (svref tree1 (- (length tree1) (bits-below idx subnodes1) 1))
						(svref tree2 (- (length tree2) (bits-below idx subnodes2) 1))
			  (add-subnode idx (rec (ch-set-node-subnode tree1 (1-bits-below idx subnodes1))
						(ch-set-node-subnode tree2 (1-bits-below idx subnodes2))
						(1+ depth)))))))
	       ;; Returns `nil' if empty.
	       (and (or (/= 0 ientry) (/= 0 isubnode))
		    (let ((extra (- new-len (+ ch-set-node-header-size ientry isubnode)))
			  ((n (if (= 0 extra) n
				(vector-remove-n-at n (+ ch-set-node-header-size ientry) extra)))))
		      (setf (ch-set-node-entry-mask n) entries)
		      (setf (ch-set-node-subnode-mask n) subnodes)
		      (setf (ch-set-node-size n) size)
		      (setf (ch-set-node-hash-value n) content-hash)
		      n))))))))
	       (ch-set-compact-node res-n)))))))

(defun ch-set-tree-diff (tree1 tree2 hash-fn compare-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn))
  (rlabels (rec tree1 tree2 0)
    (rec (tree1 tree2 depth)
      (declare (type (integer 0 64) depth))
      (cond ((null tree1) nil)
	    ((null tree2) tree1)
	    ((eq tree1 tree2) nil)
	    ((consp tree1)
	     (if (consp tree2)
		 (if (= (the fixnum (car tree1)) (the fixnum (car tree2)))
		     (let ((result (wb-set-tree-diff (cdr tree1) (cdr tree2) compare-fn)))
		       (ch-set-node-from-wb result (car tree1) depth))
		   tree1)
	       (let ((result nil))
		 ;; Assuming the collision subtree is likely to be much smaller than the regular one.
		 (do-wb-set-tree-members (v (cdr tree1))
		   (unless (ch-set-tree-contains? tree2 v hash-fn compare-fn depth)
		     (setq result (wb-set-tree-with result v compare-fn))))
		 (ch-set-node-from-wb result (car tree1) depth))))
	    ((consp tree2)
	     (do-wb-set-tree-members (v (cdr tree2))
	       (setq tree1 (ch-set-tree-less tree1 v hash-fn compare-fn depth)))
	     tree1)
	    (t
	     (let ((entries1 (ch-set-node-entry-mask tree1))
		   (entries2 (ch-set-node-entry-mask tree2))
		   (subnodes1 (ch-set-node-subnode-mask tree1))
		   (subnodes2 (ch-set-node-subnode-mask tree2))
		   ((res-len (length (the simple-vector tree1))) ; upper bound
		    ((res-n (make-array res-len :initial-element 0)))))
	       (flet ((add-entry (idx val)
			(ch-set-node-add-entry res-n idx val hash-fn))
		      (add-subnode (idx subnode)
			(ch-set-node-add-subnode res-n idx subnode hash-fn))
		      (subtree-less (subtree val)
			(ch-set-tree-less subtree val hash-fn compare-fn (1+ depth)))
		      (subtree-contains? (subtree val)
			(ch-set-tree-contains? subtree val hash-fn compare-fn (1+ depth))))
		 (do-bit-indices (idx (logior entries1 subnodes1))
		   (cond ((logbitp idx entries1)
			  (let ((val1 (ch-set-node-entry tree1 (1-bits-below idx entries1))))
			    (cond ((logbitp idx entries2)
				   (let ((val2 (ch-set-node-entry tree2 (1-bits-below idx entries2))))
				     (unless (equal?-cmp val1 val2 compare-fn)
				       (add-entry idx val1))))
				  ((logbitp idx subnodes2)
				   (let ((subnode (ch-set-node-subnode tree2 (1-bits-below idx subnodes2))))
				     (unless (subtree-contains? subnode val1)
				       (add-entry idx val1))))
				  (t (add-entry idx val1)))))
			 ((logbitp idx subnodes1)
			  (let ((subnode1 (ch-set-node-subnode tree1 (1-bits-below idx subnodes1))))
			    (cond ((logbitp idx entries2)
				   (let ((val2 (ch-set-node-entry tree2 (1-bits-below idx entries2))))
				     (add-subnode idx (subtree-less subnode1 val2))))
				  ((logbitp idx subnodes2)
				   (let ((subnode2 (ch-set-node-subnode tree2 (1-bits-below idx subnodes2))))
				     (add-subnode idx (rec subnode1 subnode2 (1+ depth)))))
				  (t (add-subnode idx subnode1))))))))
	       (ch-set-compact-node res-n)))))))

(defun ch-set-tree-diff-2 (tree1 tree2 hash-fn compare-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn))
  (rlabels (rec tree1 tree2 0)
    (rec (tree1 tree2 depth)
      (declare (type (integer 0 64) depth))
      (cond ((null tree1) (values nil tree2))
	    ((null tree2) (values tree1 nil))
	    ((eq tree1 tree2) (values nil nil))
	    ((consp tree1)
	     (if (consp tree2)
		 (if (= (the fixnum (car tree1)) (the fixnum (car tree2)))
		     (let ((result1 result2 (wb-set-tree-diff-2 (cdr tree1) (cdr tree2) compare-fn)))
		       (values (ch-set-node-from-wb result1 (car tree1) depth)
			       (ch-set-node-from-wb result2 (car tree2) depth)))
		   (values tree1 tree2))
	       (let ((result1 (cdr tree1)))
		 (do-ch-set-tree-members (v tree2)
		   (setq result1 (wb-set-tree-less result1 v compare-fn)))
		 (do-wb-set-tree-members (v (cdr tree1))
		   (setq tree2 (ch-set-tree-less tree2 v hash-fn compare-fn depth)))
		 (values (ch-set-node-from-wb result1 (car tree1) depth)
			 tree2))))
	    ((consp tree2)
	     (let ((res2 res1 (rec tree2 tree1 depth)))
	       (values res1 res2)))
	    (t
	     (let ((entries1 (ch-set-node-entry-mask tree1))
		   (entries2 (ch-set-node-entry-mask tree2))
		   (subnodes1 (ch-set-node-subnode-mask tree1))
		   (subnodes2 (ch-set-node-subnode-mask tree2))
		   ((res-len1 (length (the simple-vector tree1))) ; upper bound
		    ((res-n1 (make-array res-len1 :initial-element 0))))
		   ((res-len2 (length (the simple-vector tree2)))
		    ((res-n2 (make-array res-len2 :initial-element 0))))
		   (ientry1 0)
		   (isubnode1 0)
		   (ientry2 0)
		   (isubnode2 0))
	       (declare (fixnum ientry1 isubnode1 ientry2 isubnode2))
	       (flet ((add-entry (n idx val)
			(ch-set-node-add-entry n idx val hash-fn))
		      (add-subnode (n idx subnode)
			(ch-set-node-add-subnode n idx subnode hash-fn))
		      (subtree-less (subtree val)
			(ch-set-tree-less subtree val hash-fn compare-fn (1+ depth)))
		      (subtree-contains? (subtree val)
			(ch-set-tree-contains? subtree val hash-fn compare-fn (1+ depth))))
		 (do-bit-indices (idx (logior entries1 subnodes1 entries2 subnodes2))
		   (cond ((logbitp idx entries1)
			  (let ((val1 (ch-set-node-entry tree1 (postincf ientry1))))
			    (cond ((logbitp idx entries2)
				   (let ((val2 (ch-set-node-entry tree2 (postincf ientry2))))
				     (unless (equal?-cmp val1 val2 compare-fn)
				       (add-entry res-n1 idx val1)
				       (add-entry res-n2 idx val2))))
				  ((logbitp idx subnodes2)
				   (let ((subnode2 (ch-set-node-subnode tree2 (postincf isubnode2))))
				     (unless (subtree-contains? subnode2 val1)
				       (add-entry res-n1 idx val1))
				     (add-subnode res-n2 idx (subtree-less subnode2 val1))))
				  (t (add-entry res-n1 idx val1)))))
			 ((logbitp idx subnodes1)
			  (let ((subnode1 (ch-set-node-subnode tree1 (postincf isubnode1))))
			    (cond ((logbitp idx subnodes2)
				   (let ((subnode2 (ch-set-node-subnode tree2 (postincf isubnode2)))
					 ((new-sn1 new-sn2 (rec subnode1 subnode2 (1+ depth)))))
				     (add-subnode res-n1 idx new-sn1)
				     (add-subnode res-n2 idx new-sn2)))
				  ((logbitp idx entries2)
				   (let ((val2 (ch-set-node-entry tree2 (postincf ientry2))))
				     (add-subnode res-n1 idx (subtree-less subnode1 val2))
				     (unless (subtree-contains? subnode1 val2)
				       (add-entry res-n2 idx val2))))
				  (t (add-subnode res-n1 idx subnode1)))))
			 ((logbitp idx entries2)
			  (add-entry res-n2 idx (ch-set-node-entry tree2 (postincf ientry2))))
			 ((logbitp idx subnodes2)
			  (add-subnode res-n2 idx (ch-set-node-subnode tree2 (postincf isubnode2))))
			 (t (error "Bug in ch-set-tree-diff-2")))))
	       (values (ch-set-compact-node res-n1) (ch-set-compact-node res-n2))))))))

(defun ch-set-node-from-wb (wb-set-tree hash depth)
  (declare (optimize (speed 3) (safety 0))
	   (fixnum hash)
	   (type (integer 0 64) depth))
  (case (wb-set-tree-size wb-set-tree)
    (0 nil)
    (1 (vector (ash 1 (champ-hash-bits hash depth)) 0 1 hash (wb-set-tree-arb wb-set-tree)))
    (t (cons hash wb-set-tree))))

(defun ch-set-compact-node (n)
  (declare (optimize (speed 3) (safety 0)))
  (let ((entries (ch-set-node-entry-mask n))
	(subnodes (ch-set-node-subnode-mask n)))
    (and (or (/= entries 0) (/= subnodes 0))
	 (let ((len (length (the simple-vector n)))
	       (n-entries (logcount entries))
	       ((extra (- len ch-set-node-header-size n-entries (logcount subnodes)))))
	   (when (< extra 0)
	     (error "Bug!  Not enough space allocated for ch-map-node"))
	   (if (= extra 0) n
	     (vector-remove-n-at n (+ ch-set-node-header-size n-entries) extra))))))

(defun ch-set-tree-subset? (tree1 tree2 hash-fn compare-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn))
  (rlabels (rec tree1 tree2 0)
    (rec (tree1 tree2 depth)
      (declare (type (integer 0 64) depth))
      (cond ((null tree1) t)
	    ((null tree2) nil)
	    ((eq tree1 tree2) t)
	    ((consp tree1)
	     (if (consp tree2)
		 (wb-set-tree-subset? (cdr tree1) (cdr tree2) compare-fn)
	       (do-wb-set-tree-members (x (cdr tree1) t)
		 (unless (ch-set-tree-contains? tree2 x hash-fn compare-fn depth)
		   (return nil)))))
	    ((consp tree2)
	     (do-ch-set-tree-members (x tree1 t)
	       (unless (wb-set-tree-contains? (cdr tree2) x compare-fn)
		 (return nil))))
	    (t
	     (let ((entries1 (ch-set-node-entry-mask tree1))
		   (entries2 (ch-set-node-entry-mask tree2))
		   (subnodes1 (ch-set-node-subnode-mask tree1))
		   (subnodes2 (ch-set-node-subnode-mask tree2)))
	       (do-bit-indices (idx (logior entries1 subnodes1)
				    t)
		 (cond ((logbitp idx entries1)
			(cond ((logbitp idx entries2)
			       (let ((val1 (ch-set-node-entry tree1 (1-bits-below idx entries1)))
				     (val2 (ch-set-node-entry tree2 (1-bits-below idx entries2))))
				 (unless (equal?-cmp val1 val2 compare-fn)
				   (return nil))))
			      ((logbitp idx subnodes2)
			       (let ((val (ch-set-node-entry tree1 (1-bits-below idx entries1))))
				 (unless (ch-set-tree-contains? (ch-set-node-subnode tree2 (1-bits-below idx subnodes2))
								val hash-fn compare-fn (1+ depth))
				   (return nil))))
			      (t (return nil))))
		       ((logbitp idx subnodes1)
			(cond ((logbitp idx subnodes2)
			       (unless (rec (ch-set-node-subnode tree1 (1-bits-below idx subnodes1))
					    (ch-set-node-subnode tree2 (1-bits-below idx subnodes2))
					    (1+ depth))
				 (return nil)))
			      (t (return nil))))))))))))

(defun ch-set-tree-disjoint? (tree1 tree2 hash-fn compare-fn)
  (declare (optimize (debug 3)))
  (declare (optimize (speed 3) (safety 0))
	   (type function hash-fn compare-fn))
  (rlabels (rec tree1 tree2 0)
    (rec (tree1 tree2 depth)
      (declare (type (integer 0 64) depth))
      (cond ((or (null tree1) (null tree2)) t)
	    ((and (consp tree1) (consp tree2))
	     (wb-set-tree-disjoint? (cdr tree1) (cdr tree2) compare-fn))
	    ((or (consp tree1) (consp tree2))
	     (let ((collision-node normal-node (if (consp tree1) (values tree1 tree2) (values tree2 tree1))))
	       (do-wb-set-tree-members (x (cdr collision-node)
					  t)
		 (when (ch-set-tree-contains? normal-node x hash-fn compare-fn depth)
	    ((eq tree1 tree2) nil)
	    ((consp tree1)
	     (if (consp tree2)
		 (wb-set-tree-disjoint? (cdr tree1) (cdr tree2) compare-fn)
	       (do-wb-set-tree-members (x (cdr tree1) t)
		 (when (ch-set-tree-contains? tree2 x hash-fn compare-fn depth)
		   (return nil)))))
	    ((consp tree2)
	     (rec tree2 tree1 depth))
	    (t
	     (let ((entries1 (ch-set-node-entry-mask tree1))
		   (entries2 (ch-set-node-entry-mask tree2))
		   (subnodes1 (ch-set-node-subnode-mask tree1))
		   (subnodes2 (ch-set-node-subnode-mask tree2)))
	       (labels ((bits-below (idx mask)
			  (logcount (logand (1- (ash 1 idx)) mask))))
		 (do-bit-indices (idx (logior (logand entries1 entries2) (logand subnodes1 subnodes2)
					      (logand entries1 subnodes2) (logand subnodes1 entries2))
	       (do-bit-indices (idx (logand (logior entries1 subnodes1) (logior entries2 subnodes2))
				    t)
		 (cond ((and (logbitp idx entries1) (logbitp idx entries2))
			  (let ((val1 (svref tree1 (+ ch-set-node-header-size (bits-below idx entries1))))
				(val2 (svref tree2 (+ ch-set-node-header-size (bits-below idx entries2)))))
			(let ((val1 (ch-set-node-entry tree1 (1-bits-below idx entries1)))
			      (val2 (ch-set-node-entry tree2 (1-bits-below idx entries2))))
			  (when (equal?-cmp val1 val2 compare-fn)
			    (return nil))))
		       ((and (logbitp idx entries1) (logbitp idx subnodes2))
			  (let ((val (svref tree1 (+ ch-set-node-header-size (bits-below idx entries1)))))
			    (when (ch-set-tree-contains? (svref tree2 (- (length tree2) (bits-below idx subnodes2) 1))
			(let ((val (ch-set-node-entry tree1 (1-bits-below idx entries1))))
			  (when (ch-set-tree-contains? (ch-set-node-subnode tree2 (1-bits-below idx subnodes2))
						       val hash-fn compare-fn (1+ depth))
			    (return nil))))
		       ((and (logbitp idx subnodes1) (logbitp idx entries2))
			  (let ((val (svref tree2 (+ ch-set-node-header-size (bits-below idx entries2)))))
			    (when (ch-set-tree-contains? (svref tree1 (- (length tree1) (bits-below idx subnodes1) 1))
			(let ((val (ch-set-node-entry tree2 (1-bits-below idx entries2))))
			  (when (ch-set-tree-contains? (ch-set-node-subnode tree1 (1-bits-below idx subnodes1))
						       val hash-fn compare-fn (1+ depth))
			    (return nil))))
		       ((and (logbitp idx subnodes1) (logbitp idx subnodes2))
			  (rec (svref tree1 (- (length tree1) (bits-below idx subnodes1) 1))
			       (svref tree2 (- (length tree2) (bits-below idx subnodes2) 1))
			       (1+ depth))))))))))))
			(unless (rec (ch-set-node-subnode tree1 (1-bits-below idx subnodes1))
				     (ch-set-node-subnode tree2 (1-bits-below idx subnodes2))
				     (1+ depth))
			  (return nil)))))))))))

(defun vector-remove-n-at (vec idx n)
  (declare (optimize (speed 3) (safety 0))
	   (type simple-vector vec)
	   (type (unsigned-byte 24) idx n))
  (let ((len (length vec)))
    (declare (type fixnum len))
    (let ((new-vec (make-array (- len n))))
      (dotimes (i idx)
	(setf (svref new-vec i) (svref vec i)))
      (dotimes (i (- len idx n))
	(setf (svref new-vec (+ idx i)) (svref vec (+ idx i n))))
      new-vec)))

(defmacro do-ch-set-tree-members ((value-var tree-form &optional value-form)
				  &body body)
  (let ((body-fn (gensymx #:body-))
	(recur-fn (gensymx #:recur-)))
    `(block nil
       (labels ((,body-fn (,value-var)
		  . ,body)
		(,recur-fn (tree)
		  (when tree
		    (if (consp tree)
			(do-wb-set-tree-members (,value-var (cdr tree))
			  (,body-fn ,value-var))
		      (progn
			(dotimes (i (logcount (ch-set-node-entry-mask tree)))
			  (,body-fn (svref tree (+ i ch-set-node-header-size))))
			(dotimes (i (logcount (ch-set-node-subnode-mask tree)))
			  (,recur-fn (svref tree (- (length tree) 1 i)))))))))
	 (,recur-fn ,tree-form))
       ,value-form)))
;;; --------------------------------
;;; Verifier

(defun ch-set-tree-verify (tree hash-fn)
  (declare (optimize (debug 3)))
  (or (null tree)
      (rlabels (rec tree 0 0)
	(rec (node depth partial-hash)
	  (macrolet ((test (form)
		       `(or ,form
			    (error "Test failed at ~:A: ~S" (path depth partial-hash) ',form))))
			    (progn
			      (cerror "Ignore and proceed."
				      "Test failed at ~:A: ~S" (path depth partial-hash) ',form)
			      nil))))
	    (let ((entry-mask (ch-set-node-entry-mask node))
		  (subnode-mask (ch-set-node-subnode-mask node))
		  ((entry-bits (bit-indices entry-mask))
@@ -718,13 +1124,13 @@ (defun ch-set-tree-verify (tree hash-fn)
		   (test (not (and (> depth 0) (= 0 entry-mask) (= 1 (logcount subnode-mask))
				   (consp (svref node (1- (length node)))))))
		   (let ((size (logcount entry-mask))
			 (content-hash 0))
			 (node-hash 0))
		     (and
		       ;; Check entry value hashes
		       (gmap :and (fn (value-idx hash-bits)
				    (let ((value (svref node (+ ch-set-node-header-size value-idx)))
					  ((value-hash (hash-to-fixnum value hash-fn))))
				      (logxorf content-hash value-hash)
				      (hash-mixf node-hash value-hash)
				      (test (= (ldb (byte (* champ-hash-bits-per-level (1+ depth)) 0)
						    value-hash)
					       (new-partial-hash hash-bits depth partial-hash)))))
@@ -734,22 +1140,23 @@ (defun ch-set-tree-verify (tree hash-fn)
		       (gmap :and (fn (subnode-idx hash-bits)
				    (let ((subnode (svref node (- (length node) 1 subnode-idx))))
				      (if (consp subnode)
					  (let ((chash 0))
					  (let ((elt-hash (hash-to-fixnum (wb-set-tree-arb (cdr subnode)) hash-fn)))
					    (test (> (wb-set-tree-size (cdr subnode)) 1))
					    (do-wb-set-tree-members (v (cdr subnode))
					      (logxorf chash (hash-to-fixnum v hash-fn)))
					    (logxorf content-hash chash)
					      (test (= (hash-to-fixnum v hash-fn) elt-hash)))
					    (hash-mixf node-hash elt-hash)
					    (incf size (wb-set-tree-size (cdr subnode)))
					    (test (= (car subnode) chash)))
					    (test (= (car subnode) elt-hash)))
					(and (rec subnode (1+ depth) (new-partial-hash hash-bits depth partial-hash))
					     (progn
					       (incf size (ch-set-node-size subnode))
					       (logxorf content-hash (ch-set-node-hash-value subnode))
					       (hash-mixf node-hash (ch-set-node-hash-value subnode))
					       t)))))
			     (:arg index 0)
			     (:arg list subnode-bits))
		       ;; Finally, check size and hash
		       (test (= (ch-set-node-size node) size))
		       (test (= (ch-set-node-hash-value node) content-hash))))))))
		       (test (= (ch-set-node-hash-value node) node-hash))))))))
	(new-partial-hash (hash-bits depth partial-hash)
	  (dpb hash-bits (byte champ-hash-bits-per-level (* champ-hash-bits-per-level depth))
	       partial-hash))
@@ -765,47 +1172,100 @@ (defun ch-set-tree-verify (tree hash-fn)
;;; ================================================================================
;;; Maps

#||

It occurs to me that with a little tweaking, we could arrange for `domain' to be O(1):

- split the map node hash value into a key part and a value part
- move the value part of the hash, along with the values, to the region in between the keys and subnodes,
  so a node looks like (key-mask subnode-mask size key-hash keys... value-hash values... ...subnodes)
  (note, the key-hash and value-hash have to include resp. the key-hashes and value-hashes of the subnodes)
- for collision nodes, make them (key-hash value-hash . wb-tree)
- add another `consp' check on the cdrs of collision nodes in the set code, to deal with
  the possibility of a map collision node (when building a new set node, may want to convert)

||#

(defstruct (ch-map-node
	     (:type vector))
  (entry-mask 0 :type fixnum)
  (subnode-mask 0 :type fixnum)
  (size 0 :type fixnum) ; total number of pairs at or below this node
  (hash-value 0 :type fixnum))
(defconstant ch-map-node-header-size 4)
  (key-hash 0 :type fixnum)
  ;; This slot is used in two different ways.  For maps, it is a lazily populated cache of
  ;; the hashes of the values.  For bags, it is the total count (multiplicity).
  (value-hash nil :type (or null integer)))
(defmacro ch-map-node-bag-count (x)
  `(ch-map-node-value-hash ,x))
(defconstant ch-map-node-header-size 5)

(defun ch-map-tree-with (tree key value key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn)
;;; A collision node has the form ((key-hash . value-hash) . wb-tree), where `key-hash' is the hash
;;; value of any key -- they're all equal -- and `value-hash', if nonnull, is the mixed hash of all
;;; the values.
(deftype ch-map-tree ()
  '(or null cons simple-vector))

(declaim (ftype (function (ch-map-tree) fixnum) ch-map-tree-size))
(declaim (inline ch-map-tree-size))
(defun ch-map-tree-size (tree)
  (declare (optimize (speed 3) (safety 0)))
  (cond ((null tree) 0)
	((consp tree)
	 (wb-map-tree-size (cdr tree)))
	(t (ch-map-node-size tree))))

(declaim (inline ch-map-node-entry))
(defun ch-map-node-entry (node ientry)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn))
	   (type simple-vector node)
	   (type champ-entry-index ientry))
  (let ((entry-idx (+ ch-map-node-header-size (* 2 ientry))))
    (values (svref node entry-idx) (svref node (1+ entry-idx)))))

(declaim (inline ch-map-node-subnode))
(defun ch-map-node-subnode (node isubnode)
  (declare (optimize (speed 3) (safety 0))
	   (type simple-vector node)
	   (type champ-subnode-index isubnode))
  (svref node (- (length node) isubnode 1)))

(defun ch-map-tree-with (tree key value key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn &optional (depth 0))
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn)
	   (type (integer 0 64) depth))
  (let ((key-hash (hash-to-fixnum key key-hash-fn)))
    (declare (fixnum key-hash))
    (rlabels (rec tree key-hash 0)
      (rec (node hash-shifted depth)
    (rlabels (rec tree (ash key-hash (- (* champ-hash-bits-per-level depth))) depth)
      (rec (node hash-shifted depth &optional node-hash)
	(declare (fixnum hash-shifted)
		 (type (integer 0 64) depth))
		 (type (integer 0 64) depth)
		 (type (or null fixnum) node-hash))
	(let ((hash-bits (logand hash-shifted champ-hash-level-mask)))
	  (if (null node)
	      (vector (ash 1 hash-bits) 0 1 (logxor key-hash (hash-to-fixnum value val-hash-fn))
		      key value)
	      (vector (ash 1 hash-bits) 0 1 key-hash nil key value)
	    (if (consp node)
		;; Collision node.
		(let ((node-hash (or node-hash (hash-to-fixnum (wb-map-tree-arb-pair (cdr node)) key-hash-fn)))
		      ((wb-hash-shifted (ash node-hash (* (- champ-hash-bits-per-level) depth))))
		      (size (1+ (wb-map-tree-size (cdr node)))))
		  (declare (fixnum wb-hash-shifted hash-shifted size))
		  (if (= hash-shifted wb-hash-shifted)
		      ;; Update the collision node.
		      (let ((new-wb-tree (wb-map-tree-with (cdr node) key value key-cmp-fn val-cmp-fn)))
			(if (eq new-wb-tree (cdr node))
			    node
			  (let ((value-hash (and (cdar node)
						 (hash-mix (cdar node) (hash-to-fixnum value val-hash-fn)))))
			    (if (= (wb-map-tree-size new-wb-tree) (wb-map-tree-size (cdr node)))
				;; The key was already present, but the value was updated.
				(let ((ig old-value (wb-map-tree-lookup (cdr node) key key-cmp-fn)))
				  (declare (ignore ig))
				  (cons (cons (caar node)
					      (and value-hash
						   (hash-unmix value-hash (hash-to-fixnum old-value val-hash-fn))))
					new-wb-tree))
			      ;; New entry in collision node
			      (cons (cons (caar node) value-hash) new-wb-tree)))))
		    (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
			  (wb-hash-bits (logand wb-hash-shifted champ-hash-level-mask))
			  (key-hash (hash-mix (caar node) key-hash))
			  (value-hash (and (cdar node) (hash-mix (cdar node) (hash-to-fixnum value val-hash-fn)))))
		      (if (= hash-bits wb-hash-bits)
			  (vector 0 (ash 1 hash-bits) size key-hash value-hash
				  (rec node (ash hash-shifted (- champ-hash-bits-per-level)) (1+ depth) node-hash))
			(vector (ash 1 hash-bits) (ash 1 wb-hash-bits) size key-hash value-hash
				key value node)))))
	      ;; Normal case.
	      (let ((entry-mask (ch-map-node-entry-mask node))
		  ((entry-raw-idx (logcount (logand (1- (ash 1 hash-bits)) entry-mask)))
		   ((entry-idx (+ ch-map-node-header-size (* 2 entry-raw-idx)))))
		    ((entry-idx (+ ch-map-node-header-size (* 2 (1-bits-below hash-bits entry-mask)))))
		    (subnode-mask (ch-map-node-subnode-mask node))
		  ((subnode-raw-idx (logcount (logand (1- (ash 1 hash-bits)) subnode-mask)))
		   ((subnode-idx (- (length node) 1 subnode-raw-idx)))))
		    ((subnode-idx (- (length node) 1 (1-bits-below hash-bits subnode-mask)))))
		(if (logbitp hash-bits entry-mask)
		    ;; Entry found
		    (let ((ex-key (svref node entry-idx))
@@ -815,8 +1275,9 @@ (defun ch-map-tree-with (tree key value key-hash-fn key-cmp-fn val-hash-fn val-c
			      node ; Key found, value equal: nothing to do
			    ;; Key found, value differs: just update value
			    (let ((n (vector-update node (+ entry-idx 1) value)))
			    (logxorf (ch-map-node-hash-value n) (hash-to-fixnum ex-val val-hash-fn)
				     (hash-to-fixnum value val-hash-fn))
			      (when (ch-map-node-value-hash n)
				(hash-mixf (ch-map-node-value-hash n) (hash-unmix (hash-to-fixnum value val-hash-fn)
										  (hash-to-fixnum ex-val val-hash-fn))))
			      n))
			;; Entry with different key found: make a subnode
			(let ((hash-shifted (ash hash-shifted (- champ-hash-bits-per-level)))
@@ -824,14 +1285,13 @@ (defun ch-map-tree-with (tree key value key-hash-fn key-cmp-fn val-hash-fn val-c
			      ((ex-key-hash-shifted (ash ex-key-hash (* (- champ-hash-bits-per-level) (1+ depth))))
			       ((n2 (if (= hash-shifted ex-key-hash-shifted)
					;; Collision!  Fall back to WB-tree.
				      (cons (logxor key-hash (hash-to-fixnum value val-hash-fn) ex-key-hash
						    (hash-to-fixnum ex-val val-hash-fn))
					    (wb-map-tree-with (wb-map-tree-with nil ex-key ex-val key-cmp-fn val-cmp-fn)
					(cons (cons key-hash nil)
					      (wb-map-tree-with (wb-map-tree-with nil ex-key ex-val
										  key-cmp-fn val-cmp-fn)
								key value key-cmp-fn val-cmp-fn))
				    ;; Creates a little garbage; &&& hand-integrate later.
				      ;; Turn the entry into a subnode and recur.
				      (rec (vector (ash 1 (logand ex-key-hash-shifted champ-hash-level-mask))
						 0 1 (logxor ex-key-hash (hash-to-fixnum ex-val val-hash-fn))
						 ex-key ex-val)
						   0 1 ex-key-hash nil ex-key ex-val)
					   hash-shifted (1+ depth))))
				;; The `1+' is because we're inserting _after_ `subnode-idx', because the subnodes
				;; are in reverse order.
@@ -839,70 +1299,42 @@ (defun ch-map-tree-with (tree key value key-hash-fn key-cmp-fn val-hash-fn val-c
			  (logandc2f (ch-map-node-entry-mask n) (ash 1 hash-bits))
			  (logiorf (ch-map-node-subnode-mask n) (ash 1 hash-bits))
			  (incf (ch-map-node-size n))
			(logxorf (ch-map-node-hash-value n) key-hash (hash-to-fixnum value val-hash-fn))
			  (unless (consp n2)
			    (hash-mixf (ch-map-node-key-hash n) key-hash))
			  (when (ch-map-node-value-hash n)
			    ;; `ex-val' is now included in `n2'; we mustn't double-count it.
			    (hash-unmixf (ch-map-node-value-hash n) (hash-to-fixnum ex-val val-hash-fn))
			    (hash-mixf (ch-map-node-value-hash n) (ch-map-tree-value-hash n2 val-hash-fn)))
			  n)))
		  ;; No entry found: check for subnode
		  (if (logbitp hash-bits subnode-mask)
		      ;; Subnode found
		      (let ((subnode (svref node subnode-idx))
			  ((new-subnode
			     ;; We can create collision nodes at any level (see above).
			     (if (consp subnode)
				 (let ((wb-hash-shifted
					 (ash (hash-to-fixnum (wb-map-tree-arb-pair (cdr subnode)) key-hash-fn)
					      (* (- champ-hash-bits-per-level) (1+ depth))))
				       (hash-shifted (ash hash-shifted (- champ-hash-bits-per-level)))
				       (size (1+ (wb-map-tree-size (cdr subnode)))))
				   (declare (fixnum wb-hash-shifted hash-shifted size))
				   (if (= hash-shifted wb-hash-shifted)
				       ;; Update the collision node.
				       (let ((new-wb-tree
					       (wb-map-tree-with (cdr subnode) key value key-cmp-fn val-cmp-fn)))
					 (cond ((eq new-wb-tree (cdr subnode))
						subnode)
					       ((= (wb-map-tree-size new-wb-tree) (wb-map-tree-size (cdr subnode)))
						;; The key was already present, but the value was updated.
						(let ((ig old-value (wb-map-tree-lookup (cdr subnode) key key-cmp-fn)))
						  (declare (ignore ig))
						  (cons (logxor (the fixnum (car subnode))
								(hash-to-fixnum old-value val-hash-fn)
								(hash-to-fixnum value val-hash-fn))
							new-wb-tree)))
					       (t ; New entry in collision node
						(cons (logxor (the fixnum (car subnode)) key-hash
							      (hash-to-fixnum value val-hash-fn))
						      new-wb-tree))))
				     ;; Oh, this is fun.  We add enough levels to get to where the hashes differ.
				     (rlabels (build hash-shifted wb-hash-shifted)
				       (build (hash-shifted wb-hash-shifted)
					 (declare (fixnum hash-shifted wb-hash-shifted))
					 (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
					       (wb-hash-bits (logand wb-hash-shifted champ-hash-level-mask))
					       (content-hash (logxor (the fixnum (car subnode)) key-hash
								     (hash-to-fixnum value val-hash-fn))))
					   (if (= hash-bits wb-hash-bits)
					       (vector 0 (ash 1 hash-bits) size content-hash
						       (build (ash hash-shifted (- champ-hash-bits-per-level))
							      (ash wb-hash-shifted (- champ-hash-bits-per-level))))
					     (vector (ash 1 hash-bits) (ash 1 wb-hash-bits) size content-hash
						     key value subnode)))))))
			       (rec subnode (ash hash-shifted (- champ-hash-bits-per-level)) (1+ depth))))))
			    ((new-subnode (rec subnode (ash hash-shifted (- champ-hash-bits-per-level))
					       (1+ depth)))))
			(if (eq new-subnode subnode)
			    node ; no change
			  ;; New subnode
			  (let ((n (vector-update node subnode-idx new-subnode)))
			    ;; If only a value was updated, the subnode won't have changed size.
			    (setf (ch-map-node-size n)
				  (the fixnum (+ (ch-map-node-size n) (- (the fixnum (ch-map-tree-size new-subnode))
									 (the fixnum (ch-map-tree-size subnode))))))
			  (logxorf (ch-map-node-hash-value n) (the fixnum (ch-map-tree-hash-value subnode))
				   (the fixnum (ch-map-tree-hash-value new-subnode)))
			    (hash-mixf (ch-map-node-key-hash n) (hash-unmix (ch-map-tree-key-hash new-subnode)
									    (ch-map-tree-key-hash subnode)))
			    (when (ch-map-node-value-hash n)
			      (hash-mixf (ch-map-node-value-hash n)
					 (hash-unmix (ch-map-tree-value-hash new-subnode val-hash-fn)
						     (ch-map-tree-value-hash subnode val-hash-fn))))
			    n)))
		    ;; Neither entry nor subnode found: make new entry
		    (let ((n (vector-insert-2 node entry-idx key value)))
		      (logiorf (ch-map-node-entry-mask n) (ash 1 hash-bits))
		      (incf (ch-map-node-size n))
		    (logxorf (ch-map-node-hash-value n) key-hash (hash-to-fixnum value val-hash-fn))
		    n))))))))))
		      (hash-mixf (ch-map-node-key-hash n) key-hash)
		      (when (ch-map-node-value-hash n)
			(hash-mixf (ch-map-node-value-hash n) (hash-to-fixnum value val-hash-fn)))
		      n)))))))))))

(defun vector-rem-2-ins-1 (vec rem-idx ins-idx ins-val)
  (declare (optimize (speed 3) (safety 0))
@@ -938,91 +1370,116 @@ (defun vector-insert-2 (vec idx ins-0 ins-1)
      (setf (svref v (+ idx i 2)) (svref vec (+ idx i))))
    v))

(defun ch-map-tree-size (tree)
(declaim (ftype (function (ch-map-tree) fixnum) ch-map-tree-key-hash))
(defun ch-map-tree-key-hash (tree)
  (declare (optimize (speed 3) (safety 0)))
  (cond ((null tree) 0)
	((consp tree)
	 (wb-map-tree-size (cdr tree)))
	(t (ch-map-node-size tree))))
	((consp tree) (caar tree))
	(t (ch-map-node-key-hash tree))))

(defun ch-map-tree-hash-value (tree)
(declaim (ftype (function (ch-map-tree function) fixnum) ch-map-tree-value-hash))
(defun ch-map-tree-value-hash (tree val-hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function val-hash-fn))
  (cond ((null tree) 0)
	((consp tree) (car tree))
	(t (ch-map-node-hash-value tree))))
	((consp tree)
	 (or (cdar tree)
	     (setf (cdar tree)
		   (let ((vhash 0))
		     (do-wb-map-tree-pairs (k v (cdr tree))
		       (declare (ignore k))
		       (hash-mixf vhash (hash-to-fixnum v val-hash-fn)))
		     vhash))))
	(t
	 (or (ch-map-node-value-hash tree)
	     ;; Could happen in multiple threads, but they'll compute the same result.
	     (setf (ch-map-node-value-hash tree)
		   (let ((vhash 0))
		     (dotimes (i (logcount (ch-map-node-entry-mask tree)))
		       (let ((k v (ch-map-node-entry tree i)))
			 (declare (ignore k))
			 (hash-mixf vhash (hash-to-fixnum v val-hash-fn))))
		     (dotimes (i (logcount (ch-map-node-subnode-mask tree)))
		       (hash-mixf vhash (ch-map-tree-value-hash (ch-map-node-subnode tree i) val-hash-fn)))
		     vhash))))))

(defun ch-map-tree-less (tree key key-hash-fn key-cmp-fn val-hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn val-hash-fn))
(defun ch-map-tree-arb-pair (tree)
  (declare (optimize (speed 3) (safety 0)))
  (cond ((null tree)
	 (error "'ch-map-tree-arb' called on empty tree"))
	((consp tree)
	 (wb-map-tree-arb-pair (cdr tree)))
	((= 0 (ch-map-node-entry-mask tree))
	 ;; If there are no entries, there must be at least one subnode
	 (ch-map-tree-arb-pair (svref tree (1- (length tree)))))
	(t
	 (values (svref tree ch-map-node-header-size) (svref tree (1+ ch-map-node-header-size))))))

(defun ch-map-tree-less (tree key key-hash-fn key-cmp-fn val-hash-fn &optional (depth 0))
  (declare (optimize (speed 1) (safety 0))
	   (type function key-hash-fn key-cmp-fn val-hash-fn)
	   (type (integer 0 64) depth))
  (let ((key-hash (hash-to-fixnum key key-hash-fn)))
    (declare (fixnum key-hash))
    (rlabels (rec tree key-hash)
      (rec (node hash-shifted)
	(declare (fixnum hash-shifted))
    (rlabels (rec tree (ash key-hash (- (* champ-hash-bits-per-level depth))) depth)
      (rec (node hash-shifted depth)
	(declare (fixnum hash-shifted)
		 (type (integer 0 64) depth))
	(and node
	     (if (consp node)
		 (if (/= (the fixnum (caar node)) key-hash)
		     (values node nil)
		   (let ((new-wb-tree ex-value (wb-map-tree-less (cdr node) key key-cmp-fn)))
		     (if (eq new-wb-tree (cdr node))
			 (values node nil)
		       (let ((value-hash (and (cdar node)
					      (hash-unmix (cdar node) (hash-to-fixnum ex-value val-hash-fn)))))
			 (if (= 1 (wb-map-tree-size new-wb-tree))
			     (let ((k v (wb-map-tree-arb-pair new-wb-tree)))
			       (values (vector (ash 1 (logcount (logand hash-shifted champ-hash-level-mask)))
					       0 1 key-hash value-hash k v)
				       ex-value))
			   (values (cons (cons (caar node) value-hash) new-wb-tree)
				   ex-value))))))
	       (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
		     (entry-mask (ch-map-node-entry-mask node))
		   ((entry-raw-idx (logcount (logand (1- (ash 1 hash-bits)) entry-mask)))
		     ((entry-raw-idx (1-bits-below hash-bits entry-mask))
		      ((entry-idx (+ ch-map-node-header-size (* 2 entry-raw-idx)))))
		     (subnode-mask (ch-map-node-subnode-mask node)))
		 (if (logbitp hash-bits entry-mask)
		     (let ((ex-key (svref node entry-idx)))
		       (cond ((not (equal?-cmp ex-key key key-cmp-fn))
			    (values node 0))
			      (values node nil))
			     ((and (= (logcount entry-mask) 1) (= 0 subnode-mask))
			    (values nil (logxor key-hash (hash-to-fixnum (svref node (1+ entry-idx)) val-hash-fn))))
			      (assert (= depth 0))
			      (values nil (svref node (1+ entry-idx))))
			     (t
			    (let ((n (vector-remove-2-at node entry-idx))
				  (ex-value-hash (hash-to-fixnum (svref node (1+ entry-idx)) val-hash-fn)))
			      (let ((n (vector-remove-2-at node entry-idx)))
				(logandc2f (ch-map-node-entry-mask n) (ash 1 hash-bits))
				(decf (ch-map-node-size n))
			      (let ((kv-hash (logxor key-hash ex-value-hash)))
				(logxorf (ch-map-node-hash-value n) kv-hash)
				(values n kv-hash))))))
		 (let ((subnode-raw-idx (logcount (logand (1- (ash 1 hash-bits)) subnode-mask)))
				(hash-unmixf (ch-map-node-key-hash n) key-hash)
				(when (ch-map-node-value-hash n)
				  (hash-unmixf (ch-map-node-value-hash n)
					       (hash-to-fixnum (svref node (1+ entry-idx)) val-hash-fn)))
				(values n (svref node (1+ entry-idx)))))))
		   (let ((subnode-raw-idx (1-bits-below hash-bits subnode-mask))
			 ((subnode-idx (- (the fixnum (length node)) 1 subnode-raw-idx))))
		     (declare (fixnum subnode-raw-idx subnode-idx))
		     (if (not (logbitp hash-bits subnode-mask))
			 (values node 0)
		       (let ((subnode (svref node subnode-idx)))
		       (if (consp subnode)
			   (let ((new-wb-tree (wb-map-tree-less (cdr subnode) key key-cmp-fn)))
			     (if (eq new-wb-tree (cdr subnode))
				 (values node 0)
			       (let ((ig ex-value (wb-map-tree-lookup (cdr subnode) key key-cmp-fn))
				     ((ex-value-hash (hash-to-fixnum ex-value val-hash-fn))))
				 (declare (ignore ig))
				 (if (= 1 (wb-map-tree-size new-wb-tree))
				     ;; Removing next-to-last pair of collision node: turn remaining key/val into entry
				     (let ((rem-key rem-val (wb-map-tree-arb-pair new-wb-tree))
					   ;; `entry-idx' is still valid from above; the hash bits must be the same
					   ((n (vector-ins-2-rem-1 node entry-idx rem-key rem-val subnode-idx))))
				       (logiorf (ch-map-node-entry-mask n) (ash 1 hash-bits))
				       (logandc2f (ch-map-node-subnode-mask n) (ash 1 hash-bits))
				       (decf (ch-map-node-size n))
				       (let ((kv-hash (logxor key-hash ex-value-hash)))
					 (logxorf (ch-map-node-hash-value n) kv-hash)
					 (values n kv-hash)))
				   (let ((n (vector-update node subnode-idx
							   (cons (logxor (the fixnum (car subnode)) key-hash
									 ex-value-hash)
								 new-wb-tree))))
				     (decf (ch-map-node-size n))
				     (logxorf (ch-map-node-hash-value n) key-hash ex-value-hash)
				     (values n (logxor key-hash ex-value-hash)))))))
			 (let ((new-subnode content-hash-delta
				 (rec subnode (ash hash-shifted (- champ-hash-bits-per-level)))))
			   (declare (fixnum content-hash-delta))
			 (let ((new-subnode lookup-val
				 (rec subnode (ash hash-shifted (- champ-hash-bits-per-level)) (1+ depth))))
			   (if (eq new-subnode subnode)
			       (values node 0)
			     (let ((n (cond ((null new-subnode)
					     (let ((n (vector-remove-at node subnode-idx)))
					       (logandc2f (ch-map-node-subnode-mask n) (ash 1 hash-bits))
					       n))
			     (let ((n (cond ((consp new-subnode)
					     (vector-update node subnode-idx new-subnode))
					    ((and (= 1 (logcount (ch-map-node-entry-mask new-subnode)))
						  (= 0 (ch-map-node-subnode-mask new-subnode)))
					     ;; New subnode contains only a single entry: pull it up into this node
					     (let ((new-entry-idx
						     (+ ch-map-node-header-size
							(* 2 (logcount (logand (1- (ash 1 hash-bits)) entry-mask)))))
							(* 2 (1-bits-below hash-bits entry-mask))))
						   ((n (vector-ins-2-rem-1
							 node new-entry-idx (svref new-subnode ch-map-node-header-size)
							 (svref new-subnode (1+ ch-map-node-header-size))
@@ -1038,8 +1495,13 @@ (defun ch-map-tree-less (tree key key-hash-fn key-cmp-fn val-hash-fn)
							    (svref new-subnode ch-map-node-header-size)))
					    (t (vector-update node subnode-idx new-subnode)))))
			       (decf (ch-map-node-size n))
			       (logxorf (ch-map-node-hash-value n) content-hash-delta)
			       (values n content-hash-delta)))))))))))))))
			       (hash-mixf (ch-map-node-key-hash n) (hash-unmix (ch-map-tree-key-hash new-subnode)
									       (ch-map-tree-key-hash subnode)))
			       (when (ch-map-node-value-hash n)
				 (hash-mixf (ch-map-node-value-hash n)
					    (hash-unmix (ch-map-tree-value-hash new-subnode val-hash-fn)
							(ch-map-tree-value-hash subnode val-hash-fn))))
			       (values n lookup-val)))))))))))))))

(defun vector-remove-2-at (vec idx)
  (declare (optimize (speed 3) (safety 0))
@@ -1071,35 +1533,189 @@ (defun vector-ins-2-rem-1 (vec ins-idx ins-0 ins-1 rem-idx)
      (setf (svref v (+ ins-idx i 2)) (svref vec (+ ins-idx i))))
    (dotimes (i (- len rem-idx 1))
      (declare (fixnum i))
      (setf (svref v (+ rem-idx i 2)) (svref vec (+ rem-idx i 1))))
      (setf (svref v (the fixnum (+ rem-idx i 2))) (svref vec (+ rem-idx i 1))))
    v))

(defun ch-map-tree-lookup (tree key key-hash-fn key-cmp-fn)
(defun ch-map-tree-lookup (tree key key-hash-fn key-cmp-fn &optional (depth 0))
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn))
	   (type function key-hash-fn key-cmp-fn)
	   (type (integer 0 64) depth))
  (let ((key-hash (hash-to-fixnum key key-hash-fn)))
    (declare (fixnum key-hash))
    (rlabels (rec tree key key-hash)
    (rlabels (rec tree key (ash key-hash (- (* champ-hash-bits-per-level depth))))
      (rec (node key hash-shifted)
	(declare (fixnum hash-shifted))
	(and node
	     (if (consp node)
		 (wb-map-tree-lookup (cdr node) key key-cmp-fn)
	       (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
		     (entry-mask (ch-map-node-entry-mask node)))
		 (if (logbitp hash-bits entry-mask)
		     (let ((entry-idx (+ ch-map-node-header-size
				       (* 2 (logcount (logand (1- (ash 1 hash-bits)) entry-mask)))))
					 (* 2 (1-bits-below hash-bits entry-mask))))
			   ((ex-key (svref node entry-idx))))
		       (and (equal?-cmp ex-key key key-cmp-fn)
			    (values t (svref node (1+ entry-idx)))))
		   (let ((subnode-mask (ch-map-node-subnode-mask node)))
		     (and (logbitp hash-bits subnode-mask)
			  (let ((subnode-idx (- (the fixnum (length node))
					      1 (logcount (logand (1- (ash 1 hash-bits)) subnode-mask))))
						1 (1-bits-below hash-bits subnode-mask)))
				((subnode (svref node subnode-idx))))
			  (if (consp subnode)
			      (wb-map-tree-lookup (cdr subnode) key key-cmp-fn)
			    (rec subnode key (ash hash-shifted (- champ-hash-bits-per-level))))))))))))))

(defun ch-map-tree-index (tree key key-hash-fn key-cmp-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn))
  (let ((key-hash (hash-to-fixnum key key-hash-fn)))
    (declare (fixnum key-hash))
    (rlabels (rec tree key 0 key-hash)
      (rec (node key base hash-shifted)
	(declare (fixnum base hash-shifted))
	(and node
	     (if (consp node)
		 (let ((found? idx (wb-map-tree-rank (cdr node) key key-cmp-fn)))
		   (and found? (the fixnum (+ (the fixnum idx) base))))
	       (let ((hash-bits (logand hash-shifted champ-hash-level-mask))
		     (entry-mask (ch-map-node-entry-mask node)))
		 (if (logbitp hash-bits entry-mask)
		     (let ((ientry (1-bits-below hash-bits entry-mask))
			   ((entry-idx (+ ch-map-node-header-size (* 2 ientry)))
			    ((ex-key (svref node entry-idx)))))
		       (and (equal?-cmp ex-key key key-cmp-fn)
			    (the fixnum (+ base ientry))))
		   (let ((subnode-mask (ch-map-node-subnode-mask node)))
		     (incf base (logcount entry-mask))
		     (and (logbitp hash-bits subnode-mask)
			  (let ((isubnode (1-bits-below hash-bits subnode-mask))
				(len (length (the simple-vector node)))
				((subnode-idx (- len 1 isubnode))
				 ((subnode (svref node subnode-idx)))))
			    (dotimes (i isubnode)
			      (incf base (ch-map-tree-size (svref node (- len 1 i)))))
			    (rec subnode key base (ash hash-shifted (- champ-hash-bits-per-level))))))))))))))

(defun ch-map-tree-index-pair (tree index)
  (declare (optimize (speed 3) (safety 0)))
  (rlabels (rec tree index)
    (rec (tree index)
      (declare (fixnum index))
      (if (consp tree)
	  (wb-map-tree-rank-pair (cdr tree) index)
	(let ((len (length (the simple-vector tree)))
	      (entry-mask (ch-map-node-entry-mask tree))
	      ((n-entries (logcount entry-mask))))
	  (if (< index n-entries)
	      (let ((idx (+ ch-map-node-header-size (* 2 index))))
		(values (svref tree idx) (svref tree (1+ idx))))
	    (let ((subnode-mask (ch-map-node-subnode-mask tree)))
	      (decf index n-entries)
	      (dotimes (i (logcount subnode-mask))
		(let ((subnode (svref tree (- len i 1)))
		      ((subnode-size (ch-map-tree-size subnode))))
		  (when (< index subnode-size)
		    (return (rec subnode index)))
		  (decf index subnode-size))))))))))

(defun ch-map-tree-domain (tree key-hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn))
  (if (null tree) nil
    (rlabels (rec tree)
      (rec (node)
	(if (consp node)
	    (let ((wb-dom (wb-map-tree-domain (cdr node))))
	      (cons (hash-to-fixnum (wb-set-tree-arb wb-dom) key-hash-fn) wb-dom))
	  (let ((len (length (the simple-vector node)))
		(entry-mask (ch-map-node-entry-mask node))
		(subnode-mask (ch-map-node-subnode-mask node))
		((nentries (logcount entry-mask))
		 (nsubnodes (logcount subnode-mask))
		 ((res-len (+ ch-set-node-header-size nentries nsubnodes))
		  ((n (make-array res-len)))))
		(hash 0))
	    (setf (ch-set-node-entry-mask n) entry-mask)
	    (setf (ch-set-node-subnode-mask n) subnode-mask)
	    (setf (ch-set-node-size n) (ch-map-node-size node))
	    (dotimes (i nentries)
	      (let ((x (svref node (+ ch-map-node-header-size (* 2 i)))))
		(setf (svref n (+ ch-set-node-header-size i)) x)
		(hash-mixf hash (hash-to-fixnum x key-hash-fn))))
	    (dotimes (i nsubnodes)
	      (let ((new-subnode (rec (svref node (- len i 1)))))
		(setf (svref n (- res-len i 1)) new-subnode)
		(hash-mixf hash (ch-set-tree-hash-value new-subnode))))
	    (setf (ch-set-node-hash-value n) hash)
	    n))))))

(defun ch-map-tree-compare (tree1 tree2 key-cmp-fn val-hash-fn val-cmp-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-cmp-fn val-hash-fn val-cmp-fn))
  (if (eq tree1 tree2) ':equal
    (let ((size1 (ch-map-tree-size tree1))
	  (size2 (ch-map-tree-size tree2)))
      (cond
	((< size1 size2) ':less)
	((> size1 size2) ':greater)
	(t
	 (let ((khash1 (ch-map-tree-key-hash tree1))
	       (khash2 (ch-map-tree-key-hash tree2)))
	   (cond
	     ((< khash1 khash2) ':less)
	     ((> khash1 khash2) ':greater)
	     (t
	      (let ((vhash1 (ch-map-tree-value-hash tree1 val-hash-fn))
		    (vhash2 (ch-map-tree-value-hash tree2 val-hash-fn)))
		(cond
		  ((< vhash1 vhash2) ':less)
		  ((> vhash1 vhash2) ':greater)
		  ((consp tree1)
		   (if (consp tree2) (wb-map-tree-compare (cdr tree1) (cdr tree2) key-cmp-fn val-cmp-fn)
		     ':less))
		  ((consp tree2) ':greater)
		  (t
		   (let ((entries1 (ch-map-node-entry-mask tree1))
			 (entries2 (ch-map-node-entry-mask tree2))
			 (subnodes1 (ch-map-node-subnode-mask tree1))
			 (subnodes2 (ch-map-node-subnode-mask tree2)))
		     (cond ((< entries1 entries2) ':less)
			   ((> entries1 entries2) ':greater)
			   ((< subnodes1 subnodes2) ':less)
			   ((> subnodes1 subnodes2) ':greater)
			   (t
			    ;; It's astronomically unlikely that we'll get here unless the trees are actually
			    ;; equal... but we still have to check.
			    (let ((default ':equal)
				  (len (length (the simple-vector tree1))))
			      (dotimes (i (logcount entries1))
				(let ((k1 (svref tree1 (+ ch-map-node-header-size (* 2 i))))
				      (v1 (svref tree1 (+ ch-map-node-header-size (1+ (* 2 i)))))
				      (k2 (svref tree2 (+ ch-map-node-header-size (* 2 i))))
				      (v2 (svref tree2 (+ ch-map-node-header-size (1+ (* 2 i)))))
				      ((key-cmp (funcall key-cmp-fn k1 k2))))
				  (when (member key-cmp '(:less :greater))
				    (return-from ch-map-tree-compare key-cmp))
				  (when (eq key-cmp ':unequal)
				    (setq default ':unequal))
				  (let ((val-cmp (funcall val-cmp-fn v1 v2)))
				    (when (member val-cmp '(:less :greater))
				      (return-from ch-map-tree-compare val-cmp))
				    (when (eq val-cmp ':unequal)
				      (setq default ':unequal)))))
			      (dotimes (i (logcount subnodes1))
				(let ((cmp (ch-map-tree-compare (svref tree1 (- len i 1)) (svref tree2 (- len i 1))
								key-cmp-fn val-hash-fn val-cmp-fn)))
				  (ecase cmp
				    (:equal)
				    (:unequal
				      (setq default ':unequal))
				    ((:less :greater)
				      (return-from ch-map-tree-compare cmp)))))
			      default)))))))))))))))


;;; --------------------------------
;;; Iteration primitives

(defmacro do-ch-map-tree-pairs ((key-var value-var tree-form &optional value-form)
				&body body)
  (let ((body-fn (gensymx #:body-))
@@ -1112,23 +1728,672 @@ (defmacro do-ch-map-tree-pairs ((key-var value-var tree-form &optional value-for
		    (if (consp tree)
			(do-wb-map-tree-pairs (,key-var ,value-var (cdr tree))
			  (,body-fn ,key-var ,value-var))
		      (progn
		      (let ((len (the fixnum (length (the simple-vector tree)))))
			(dotimes (i (logcount (ch-map-node-entry-mask tree)))
			  (let ((idx (+ (* 2 i) ch-map-node-header-size)))
			    (,body-fn (svref tree idx) (svref tree (1+ idx)))))
			(dotimes (i (logcount (ch-map-node-subnode-mask tree)))
			  (,recur-fn (svref tree (- (the fixnum (length tree)) 1 i)))))))))
			  (,recur-fn (svref tree (- len 1 i)))))))))
	 (declare (inline ,body-fn))
	 (,recur-fn ,tree-form))
       ,value-form)))

(defun ch-map-tree-verify (tree)
  (declare (optimize (debug 3)))
;;; ----------------
;;; Stateful iterator

(defun make-ch-map-tree-iterator (tree)
  (let ((iter (make-ch-map-tree-iterator-internal tree)))
    (lambda (op)
      (ecase op
	(:get (ch-map-tree-iterator-get iter))
	(:done? (ch-map-tree-iterator-done? iter))
	(:more? (not (ch-map-tree-iterator-done? iter)))))))

(defun make-ch-map-tree-iterator-internal (tree)
  (declare (optimize (speed 3) (safety 0)))
  (let ((iter (make-array (+ 1 (* 2 (ceiling (integer-length most-positive-fixnum) champ-hash-bits-per-level))))))
    (if (null tree)
	(setf (svref iter 0) -1)
      (progn
	(setf (svref iter 0) 1) ; the stack pointer
	(setf (svref iter 1) tree)
	(setf (svref iter 2) 0)
	(ch-map-tree-iterator-canonicalize iter)))
    iter))

(defun ch-map-tree-iterator-canonicalize (iter)
  (declare (optimize (speed 3) (safety 0)))
  (let ((sp (svref iter 0))
	((node (svref iter sp))
	 (idx (svref iter (1+ sp)))))
    (declare (type (or null fixnum) idx))
    (when (if (null idx)
	      (wb-map-tree-iterator-done? (svref iter sp))
	    (= idx (logcount (logior (ch-map-node-entry-mask node) (ch-map-node-subnode-mask node)))))
      (decf sp 2)
      (unless (< sp 0)
	(setq node (svref iter sp))
	(setq idx (svref iter (1+ sp)))))
    (unless (< sp 0)
      (loop
	(when (null idx)
	  (return))
	(let ((n-entries (logcount (ch-map-node-entry-mask node)))
	      (n-subnodes (logcount (ch-map-node-subnode-mask node))))
	  (when (< idx n-entries)
	    (return))
	  (let ((len (length (the simple-vector node))))
	    (setq node (svref node (- len (- idx n-entries) 1)))
	    (incf idx)
	    (unless (= idx (+ n-entries n-subnodes)) ; TCO
	      (setf (svref iter (1+ sp)) idx)
	      (incf sp 2))
	    (if (consp node)
		(setq node (make-wb-map-tree-iterator-internal (cdr node))
		      idx nil)
	      (setq idx 0))
	    (setf (svref iter sp) node)
	    (setf (svref iter (1+ sp)) idx)))))
    (setf (svref iter 0) sp)))

(defun ch-map-tree-iterator-done? (iter)
  (declare (optimize (speed 3) (safety 0)))
  (< (the fixnum (svref iter 0)) 0))

(defun ch-map-tree-iterator-get (iter)
  (declare (optimize (speed 3) (safety 0)))
  (let ((sp (svref iter 0)))
    (declare (fixnum sp))
    (and (> sp 0)
	 (let ((node (svref iter sp))
	       (idx (svref iter (1+ sp))))
	   (declare (type (or null fixnum) idx))
	   (if (null idx)
	       (let ((key val (wb-map-tree-iterator-get node)))
		 (ch-map-tree-iterator-canonicalize iter)
		 (values key val t))
	     (let ((entry-idx (+ ch-map-node-header-size (the fixnum (* 2 idx)))))
	       (setf (svref iter (1+ sp)) (1+ idx))
	       (ch-map-tree-iterator-canonicalize iter)
	       (values (svref node entry-idx) (svref node (1+ entry-idx))
		       t)))))))

;;; ----------------
;;; Functional iterator

(defun ch-map-tree-fun-iter (tree)
  (declare (optimize (speed 3) (safety 0)))
  (rlabels (walk tree (lambda (op)
			(ecase op
			  (:first (values nil nil))
			  (:empty? t)
			  (:more? nil))))
    (walk (node cont)
      (if (consp node)
	  (wb-map-tree-fun-iter (cdr node) cont)
	(let ((n-entries (logcount (ch-map-node-entry-mask node)))
	      (n-subnodes (logcount (ch-map-node-subnode-mask node))))
	  (rlabels (entry 0)
	    (entry (i)
	      (declare (fixnum i))
	      (if (< i n-entries)
		  (lambda (op)
		    (ecase op
		      (:first (let ((entry-idx (+ ch-map-node-header-size (the fixnum (* 2 i)))))
				(values (svref node entry-idx) (svref node (1+ entry-idx)) t)))
		      (:rest (entry (1+ i)))
		      (:empty? nil)
		      (:more? t)))
		(subnode 0)))
	    (subnode (i)
	      (declare (fixnum i))
	      (if (< i n-subnodes)
		  (walk (svref node (- (+ ch-map-node-header-size (* 2 n-entries) n-subnodes)
				       i 1))
			(lambda (op) (funcall (the function (subnode (1+ i))) op)))
		cont))))))))

(defun ch-map-tree-rev-fun-iter (tree)
  (declare (optimize (speed 3) (safety 0)))
  (rlabels (walk tree (lambda (op)
			(ecase op
			  (:first (values nil nil))
			  (:empty? t)
			  (:more? nil))))
    (walk (node cont)
      (if (consp node)
	  (wb-map-tree-rev-fun-iter (cdr node) cont)
	(let ((n-entries (logcount (ch-map-node-entry-mask node)))
	      (n-subnodes (logcount (ch-map-node-subnode-mask node))))
	  (rlabels (subnode (1- n-subnodes))
	    (entry (i)
	      (declare (fixnum i))
	      (if (>= i 0)
		  (lambda (op)
		    (ecase op
		      (:first (let ((entry-idx (+ ch-map-node-header-size (the fixnum (* 2 i)))))
				(values (svref node entry-idx) (svref node (1+ entry-idx)) t)))
		      (:rest (entry (1- i)))
		      (:empty? nil)
		      (:more? t)))
		cont))
	    (subnode (i)
	      (declare (fixnum i))
	      (if (>= i 0)
		  (walk (svref node (- (+ ch-map-node-header-size (* 2 n-entries) n-subnodes)
				       i 1))
			(lambda (op) (funcall (the function (subnode (1- i))) op)))
		(entry (1- n-entries))))))))))


;;; --------------------------------
;;; Union, intersection, set-difference, subset?, disjoint?

(declaim (inline ch-map-node-add-entry))
(defun ch-map-node-add-entry (n idx key val key-hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type champ-bit-index idx)
	   (type function key-hash-fn))
  (let ((entry-idx (+ ch-map-node-header-size (* 2 (logcount (ch-map-node-entry-mask n))))))
    (setf (svref n entry-idx) key)
    (setf (svref n (1+ entry-idx)) val))
  (logiorf (ch-map-node-entry-mask n) (ash 1 idx))
  (incf (ch-map-node-size n))
  (hash-mixf (ch-map-node-key-hash n) (hash-to-fixnum key key-hash-fn)))

(declaim (inline ch-map-node-add-subnode))
(defun ch-map-node-add-subnode (n idx subnode key-hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type champ-bit-index idx)
	   (type function key-hash-fn))
  (when subnode
    (if (and (not (consp subnode))
	     (= 1 (logcount (ch-map-node-entry-mask subnode)))
	     (= 0 (ch-map-node-subnode-mask subnode)))
	;; `subnode' contains only an entry -- pull it up.
	(ch-map-node-add-entry n idx (svref subnode ch-map-node-header-size)
			       (svref subnode (1+ ch-map-node-header-size)) key-hash-fn)
      (progn
	(when (and (not (consp subnode))
		   (= 0 (ch-map-node-entry-mask subnode))
		   (= 1 (logcount (ch-map-node-subnode-mask subnode)))
		   (consp (svref subnode (1- (length subnode)))))
	  ;; `subnode' contains only a collision subnode -- pull it up.
	  (setq subnode (svref subnode (1- (length subnode)))))
	(setf (svref n (- (length (the simple-vector n))
			  (logcount (ch-map-node-subnode-mask n)) 1))
	      subnode)
	(logiorf (ch-map-node-subnode-mask n) (ash 1 idx))
	(incf (ch-map-node-size n) (ch-map-tree-size subnode))
	(hash-mixf (ch-map-node-key-hash n) (ch-map-tree-key-hash subnode))))))

(defun ch-map-tree-union (tree1 tree2 val-fn key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function val-fn key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn))
  (rlabels (rec tree1 tree2 val-fn 0)
    (rec (tree1 tree2 val-fn depth)
      (declare (type (integer 0 64) depth)
	       (type function val-fn))
      (cond ((null tree1) tree2)
	    ((null tree2) tree1)
	    ((eq tree1 tree2) tree1)
	    ((and (consp tree1) (consp tree2))
	     (if (= (the fixnum (caar tree1)) (the fixnum (caar tree2)))
		 (let ((result (wb-map-tree-union (cdr tree1) (cdr tree2) val-fn key-cmp-fn)))
		   (ch-map-node-from-wb result (caar tree1) depth))
	       (let ((bits1 (champ-hash-bits (the fixnum (caar tree1)) depth))
		     (bits2 (champ-hash-bits (the fixnum (caar tree2)) depth))
		     (size (+ (wb-map-tree-size (cdr tree1)) (wb-map-tree-size (cdr tree2))))
		     (key-hash (hash-mix (caar tree1) (caar tree2))))
		 (declare (fixnum size))
		 (if (= bits1 bits2)
		     (vector 0 (ash 1 bits1) size key-hash nil (rec tree1 tree2 val-fn (1+ depth)))
		   (let ((subnode0 subnode1 (swap-if (> bits1 bits2) tree1 tree2)))
		     (vector 0 (logior (ash 1 bits1) (ash 1 bits2)) size key-hash nil subnode1 subnode0))))))
	    ((consp tree1)
	     (do-wb-map-tree-pairs (k1 v1 (cdr tree1))
	       (let ((v2? v2 (ch-map-tree-lookup tree2 k1 key-hash-fn key-cmp-fn depth)))
		 (if v2?
		     (let ((new-v second-val (funcall val-fn v1 v2)))
		       (if (eq second-val ':no-value)
			   (setq tree2 (ch-map-tree-less tree2 k1 key-hash-fn key-cmp-fn val-hash-fn depth))
			 (setq tree2 (ch-map-tree-with tree2 k1 new-v key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn
						       depth))))
		   (setq tree2 (ch-map-tree-with tree2 k1 v1 key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn depth)))))
	     tree2)
	    ((consp tree2)
	     (rec tree2 tree1 (fn (x y) (funcall val-fn y x)) depth))
	    (t
	     (let ((entries1 (ch-map-node-entry-mask tree1))
		   (entries2 (ch-map-node-entry-mask tree2))
		   (subnodes1 (ch-map-node-subnode-mask tree1))
		   (subnodes2 (ch-map-node-subnode-mask tree2))
		   ((all-entries (logior entries1 entries2))
		    (all-subnodes (logior subnodes1 subnodes2))
		    ((everything (logior all-entries all-subnodes))
		     ;; The `:no-value' feature creates the possibility that a subnode, on one or both sides,
		     ;; will change to an entry; in the worst case, this could happen to all of them.
		     ((res-len (+ ch-map-node-header-size (* 2 (logcount everything))))
		      ((res-n (make-array res-len :initial-element 0))))))
		   (ientry1 0)
		   (isubnode1 0)
		   (ientry2 0)
		   (isubnode2 0))
	       (declare (fixnum ientry1 isubnode1 ientry2 isubnode2))
	       (setf (ch-map-node-value-hash res-n) nil)
	       (flet ((add-entry (idx key val)
			(ch-map-node-add-entry res-n idx key val key-hash-fn))
		      (add-subnode (idx subnode)
			(ch-map-node-add-subnode res-n idx subnode key-hash-fn)
			nil)  ; hush, SBCL
		      (subtree-lookup (tree key)
			(ch-map-tree-lookup tree key key-hash-fn key-cmp-fn (1+ depth)))
		      (subtree-with (subtree key value)
			(ch-map-tree-with subtree key value key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn
					  (1+ depth)))
		      (subtree-less (subtree key)
			(ch-map-tree-less subtree key key-hash-fn key-cmp-fn val-hash-fn (1+ depth))))
		 (do-bit-indices (idx everything)
		   (cond ((and (logbitp idx entries1) (logbitp idx entries2))
			  (let ((key1 val1 (ch-map-node-entry tree1 (postincf ientry1)))
				(key2 val2 (ch-map-node-entry tree2 (postincf ientry2))))
			    (if (equal?-cmp key1 key2 key-cmp-fn)
				(let ((new-val second-val (funcall val-fn val1 val2)))
				  (unless (eq second-val ':no-value)
				    (add-entry idx key1 new-val)))
			      (add-subnode idx (subtree-with (subtree-with nil key1 val1) key2 val2)))))
			 ((logbitp idx entries1)
			  (let ((key1 val1 (ch-map-node-entry tree1 (postincf ientry1))))
			    (if (logbitp idx subnodes2)
				(let ((subnode2 (ch-map-node-subnode tree2 (postincf isubnode2)))
				      ((val2? val2 (subtree-lookup subnode2 key1))))
				  (if val2?
				      (let ((new-val second-val (funcall val-fn val1 val2)))
					(if (eq second-val ':no-value)
					    (add-subnode idx (subtree-less subnode2 key1))
					  (add-subnode idx (subtree-with subnode2 key1 new-val))))
				    (add-subnode idx (subtree-with subnode2 key1 val1))))
			      (add-entry idx key1 val1))))
			 ((logbitp idx entries2)
			  (let ((key2 val2 (ch-map-node-entry tree2 (postincf ientry2))))
			    (if (logbitp idx subnodes1)
				(let ((subnode1 (ch-map-node-subnode tree1 (postincf isubnode1)))
				      ((val1? val1 (subtree-lookup subnode1 key2))))
				  (if val1?
				      (let ((new-val second-val (funcall val-fn val1 val2)))
					(if (eq second-val ':no-value)
					    (add-subnode idx (subtree-less subnode1 key2))
					  (add-subnode idx (subtree-with subnode1 key2 new-val))))
				    (add-subnode idx (subtree-with subnode1 key2 val2))))
			      (add-entry idx key2 val2))))
			 ((and (logbitp idx subnodes1) (logbitp idx subnodes2))
			  (add-subnode idx (rec (ch-map-node-subnode tree1 (postincf isubnode1))
						(ch-map-node-subnode tree2 (postincf isubnode2))
						val-fn (1+ depth))))
			 ((logbitp idx subnodes1)
			  (add-subnode idx (ch-map-node-subnode tree1 (postincf isubnode1))))
			 ((logbitp idx subnodes2)
			  (add-subnode idx (ch-map-node-subnode tree2 (postincf isubnode2))))
			 (t (error "Bug in 'ch-map-tree-union'")))))
	       ;; When two entries meet and become a subnode, we no longer need the value slot.
	       (ch-map-compact-node res-n)))))))

(defun ch-map-tree-intersection (tree1 tree2 val-fn key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function val-fn key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn))
  (rlabels (rec tree1 tree2 val-fn 0)
    (rec (tree1 tree2 val-fn depth)
      (declare (type (integer 0 64) depth)
	       (type function val-fn))
      (cond ((or (null tree1) (null tree2)) nil)
	    ((eq tree1 tree2) tree1)
	    ((and (consp tree1) (consp tree2))
	     (and (= (the fixnum (caar tree1)) (the fixnum (caar tree2)))
		  (let ((result (wb-map-tree-intersect (cdr tree1) (cdr tree2) val-fn key-cmp-fn)))
		    (ch-map-node-from-wb result (caar tree1) depth))))
	    ((consp tree1)
	     (let ((result nil))
	       (do-wb-map-tree-pairs (k1 v1 (cdr tree1))
		 (let ((v2? v2 (ch-map-tree-lookup tree2 k1 key-hash-fn key-cmp-fn depth)))
		   (when v2?
		     (let ((new-v second-val (funcall val-fn v1 v2)))
		       (unless (eq second-val ':no-value)
			 (setq result (ch-map-tree-with result k1 new-v key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn
							depth)))))))
	       result))
	    ((consp tree2)
	     (rec tree2 tree1 (fn (x y) (funcall val-fn y x)) depth))
	    (t
	     (let ((entries1 (ch-map-node-entry-mask tree1))
		   (entries2 (ch-map-node-entry-mask tree2))
		   (subnodes1 (ch-map-node-subnode-mask tree1))
		   (subnodes2 (ch-map-node-subnode-mask tree2))
		   ((combined-mask (logand (logior entries1 subnodes1) (logior entries2 subnodes2)))
		    ;; The result can be longer than either input, because the intersection of two subnodes
		    ;; could be an entry.
		    ((res-len (+ ch-map-node-header-size (* 2 (logcount combined-mask))))
		     ((res-n (make-array res-len :initial-element 0))))))
	       (setf (ch-map-node-value-hash res-n) nil)
	       (flet ((add-entry (idx key val)
			(ch-map-node-add-entry res-n idx key val key-hash-fn))
		      (add-subnode (idx subnode)
			(ch-map-node-add-subnode res-n idx subnode key-hash-fn))
		      (subtree-lookup (tree key)
			(ch-map-tree-lookup tree key key-hash-fn key-cmp-fn (1+ depth))))
		 (do-bit-indices (idx combined-mask)
		   (cond ((and (logbitp idx entries1) (logbitp idx entries2))
			  (let ((key1 val1 (ch-map-node-entry tree1 (1-bits-below idx entries1)))
				(key2 val2 (ch-map-node-entry tree2 (1-bits-below idx entries2))))
			    (when (equal?-cmp key1 key2 key-cmp-fn)
			      (let ((new-val second-val (funcall val-fn val1 val2)))
				(unless (eq second-val ':no-value)
				  (add-entry idx key1 new-val))))))
			 ((and (logbitp idx entries1) (logbitp idx subnodes2))
			  (let ((key1 val1 (ch-map-node-entry tree1 (1-bits-below idx entries1)))
				(subnode2 (ch-map-node-subnode tree2 (1-bits-below idx subnodes2)))
				((val2? val2 (subtree-lookup subnode2 key1))))
			    (when val2?
			      (let ((new-val second-val (funcall val-fn val1 val2)))
				(unless (eq second-val ':no-value)
				  (add-entry idx key1 new-val))))))
			 ((and (logbitp idx subnodes1) (logbitp idx entries2))
			  (let ((key2 val2 (ch-map-node-entry tree2 (1-bits-below idx entries2)))
				(subnode1 (ch-map-node-subnode tree1 (1-bits-below idx subnodes1)))
				((val1? val1 (subtree-lookup subnode1 key2))))
			    (when val1?
			      (let ((new-val second-val (funcall val-fn val1 val2)))
				(unless (eq second-val ':no-value)
				  (add-entry idx key2 new-val))))))
			 ((and (logbitp idx subnodes1) (logbitp idx subnodes2))
			  (add-subnode idx (rec (ch-map-node-subnode tree1 (1-bits-below idx subnodes1))
						(ch-map-node-subnode tree2 (1-bits-below idx subnodes2))
						val-fn (1+ depth))))))
		 (ch-map-compact-node res-n))))))))

(defun ch-map-tree-diff-2 (tree1 tree2 key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn))
  (rlabels (rec tree1 tree2 0)
    (rec (tree1 tree2 depth)
      (declare (type (integer 0 64) depth))
      (cond ((null tree1) (values nil tree2))
	    ((null tree2) (values tree1 nil))
	    ((eq tree1 tree2) (values nil nil))
	    ((consp tree1)
	     (if (consp tree2)
		 (if (= (the fixnum (caar tree1)) (the fixnum (caar tree2)))
		     (let ((result1 result2 (wb-map-tree-diff-2 (cdr tree1) (cdr tree2) key-cmp-fn val-cmp-fn)))
		       (values (ch-map-node-from-wb result1 (caar tree1) depth)
			       (ch-map-node-from-wb result2 (caar tree2) depth)))
		   (values tree1 tree2))
	       (let ((result1 nil)
		     (result2 nil))
		 (do-wb-map-tree-pairs (k v1 (cdr tree1))
		   (let ((v2? v2 (ch-map-tree-lookup tree2 k key-hash-fn key-cmp-fn depth)))
		     (unless (and v2? (equal?-cmp v1 v2 val-cmp-fn))
		       (setq result1 (wb-map-tree-with result1 k v1 key-cmp-fn val-cmp-fn)))))
		 (do-ch-map-tree-pairs (k v2 tree2)
		   (let ((v1? v1 (wb-map-tree-lookup (cdr tree1) k key-cmp-fn)))
		     (unless (and v1? (equal?-cmp v1 v2 val-cmp-fn))
		       (setq result2 (ch-map-tree-with result2 k v2 key-hash-fn key-cmp-fn val-hash-fn val-cmp-fn
						       depth)))))
		 (values (ch-map-node-from-wb result1 (caar tree1) depth)
			 result2))))
	    ((consp tree2)
	     (let ((res2 res1 (rec tree2 tree1 depth)))
	       (values res1 res2)))
	    (t
	     (let ((entries1 (ch-map-node-entry-mask tree1))
		   (entries2 (ch-map-node-entry-mask tree2))
		   (subnodes1 (ch-map-node-subnode-mask tree1))
		   (subnodes2 (ch-map-node-subnode-mask tree2))
		   ((res-len1 (+ ch-map-node-header-size (* 2 (logcount (logior entries1 subnodes1)))))
		    ((res-n1 (make-array res-len1 :initial-element 0))))
		   ((res-len2 (+ ch-map-node-header-size (* 2 (logcount (logior entries2 subnodes2)))))
		    ((res-n2 (make-array res-len2 :initial-element 0))))
		   (ientry1 0)
		   (isubnode1 0)
		   (ientry2 0)
		   (isubnode2 0))
	       (declare (fixnum ientry1 isubnode1 ientry2 isubnode2))
	       (setf (ch-map-node-value-hash res-n1) nil)
	       (setf (ch-map-node-value-hash res-n2) nil)
	       (flet ((add-entry (n idx key val)
			(ch-map-node-add-entry n idx key val key-hash-fn))
		      (add-subnode (n idx subnode)
			(ch-map-node-add-subnode n idx subnode key-hash-fn))
		      (subtree-less (subtree key)
			(ch-map-tree-less subtree key key-hash-fn key-cmp-fn val-hash-fn (1+ depth)))
		      (subtree-lookup (subtree key)
			(ch-map-tree-lookup subtree key key-hash-fn key-cmp-fn (1+ depth))))
		 (do-bit-indices (idx (logior entries1 subnodes1 entries2 subnodes2))
		   (cond ((logbitp idx entries1)
			  (let ((key1 val1 (ch-map-node-entry tree1 (postincf ientry1))))
			    (cond ((logbitp idx entries2)
				   (let ((key2 val2 (ch-map-node-entry tree2 (postincf ientry2))))
				     (unless (and (equal?-cmp key1 key2 key-cmp-fn) (equal?-cmp val1 val2 val-cmp-fn))
				       (add-entry res-n1 idx key1 val1)
				       (add-entry res-n2 idx key2 val2))))
				  ((logbitp idx subnodes2)
				   (let ((subnode2 (ch-map-node-subnode tree2 (postincf isubnode2)))
					 ((val2? val2 (subtree-lookup subnode2 key1))))
				     (if (and val2? (equal?-cmp val1 val2 val-cmp-fn))
					 (add-subnode res-n2 idx (subtree-less subnode2 key1))
				       (progn
					 (add-entry res-n1 idx key1 val1)
					 (add-subnode res-n2 idx subnode2)))))
				  (t (add-entry res-n1 idx key1 val1)))))
			 ((logbitp idx subnodes1)
			  (let ((subnode1 (ch-map-node-subnode tree1 (postincf isubnode1))))
			    (cond ((logbitp idx subnodes2)
				   (let ((subnode2 (ch-map-node-subnode tree2 (postincf isubnode2)))
					 ((new-sn1 new-sn2 (rec subnode1 subnode2 (1+ depth)))))
				     (add-subnode res-n1 idx new-sn1)
				     (add-subnode res-n2 idx new-sn2)))
				  ((logbitp idx entries2)
				   (let ((key2 val2 (ch-map-node-entry tree2 (postincf ientry2)))
					 ((val1? val1 (subtree-lookup subnode1 key2))))
				     (if (and val1? (equal?-cmp val1 val2 val-cmp-fn))
					 (add-subnode res-n1 idx (subtree-less subnode1 key2))
				       (progn
					 (add-subnode res-n1 idx subnode1)
					 (add-entry res-n2 idx key2 val2)))))
				  (t (add-subnode res-n1 idx subnode1)))))
			 ((logbitp idx entries2)
			  (let ((key val (ch-map-node-entry tree2 (postincf ientry2))))
			    (add-entry res-n2 idx key val)))
			 ((logbitp idx subnodes2)
			  (add-subnode res-n2 idx (ch-map-node-subnode tree2 (postincf isubnode2))))
			 (t (error "Bug in ch-map-tree-diff")))))
	       (values (ch-map-compact-node res-n1) (ch-map-compact-node res-n2))))))))

(defun ch-map-tree-restrict (map-tree set-tree key-hash-fn key-cmp-fn val-hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn val-hash-fn))
  (rlabels (rec map-tree set-tree 0)
    (rec (map-tree set-tree depth)
      (declare (type (integer 0 64) depth))
      (cond ((or (null map-tree) (null set-tree)) nil)
	    ((and (consp map-tree) (consp set-tree))
	     (and (= (the fixnum (caar map-tree)) (the fixnum (car set-tree)))
		  (let ((result (wb-map-tree-restrict (cdr map-tree) (cdr set-tree) key-cmp-fn)))
		    (ch-map-node-from-wb result (car set-tree) depth))))
	    ;; I figure the collision nodes are probably the smaller of the two.
	    ((consp map-tree)
	     (let ((result nil))
	       (do-wb-map-tree-pairs (k v (cdr map-tree))
		 (when (ch-set-tree-contains? set-tree k key-hash-fn key-cmp-fn depth)
		   (setq result (ch-map-tree-with result k v key-hash-fn key-cmp-fn val-hash-fn (fn (_ _)) depth))))
	       result))
	    ((consp set-tree)
	     (let ((result nil))
	       (do-wb-set-tree-members (k (cdr set-tree))
		 (let ((v? v (ch-map-tree-lookup map-tree k key-hash-fn key-cmp-fn depth)))
		   (when v?
		     (setq result (ch-map-tree-with result k v key-hash-fn key-cmp-fn val-hash-fn (fn (_ _))
						    depth)))))
	       result))
	    (t
	     (let ((entries1 (ch-map-node-entry-mask map-tree))
		   (entries2 (ch-set-node-entry-mask set-tree))
		   (subnodes1 (ch-map-node-subnode-mask map-tree))
		   (subnodes2 (ch-set-node-subnode-mask set-tree))
		   ((combined-mask (logand (logior entries1 subnodes1) (logior entries2 subnodes2)))
		    ;; The result can be longer than either input, because the restriction of two subnodes
		    ;; could be an entry.
		    ((res-len (+ ch-map-node-header-size (* 2 (logcount combined-mask))))
		     ((res-n (make-array res-len :initial-element 0))))))
	       (setf (ch-map-node-value-hash res-n) nil)
	       (flet ((add-entry (idx key val)
			(ch-map-node-add-entry res-n idx key val key-hash-fn))
		      (add-subnode (idx subnode)
			(ch-map-node-add-subnode res-n idx subnode key-hash-fn))
		      (map-lookup (map-subtree key)
			(ch-map-tree-lookup map-subtree key key-hash-fn key-cmp-fn (1+ depth)))
		      (set-contains? (set-subtree key)
			(ch-set-tree-contains? set-subtree key key-hash-fn key-cmp-fn (1+ depth))))
		 (do-bit-indices (idx combined-mask)
		   (cond ((and (logbitp idx entries1) (logbitp idx entries2))
			  (let ((key1 val1 (ch-map-node-entry map-tree (1-bits-below idx entries1)))
				(key2 (ch-set-node-entry set-tree (1-bits-below idx entries2))))
			    (when (equal?-cmp key1 key2 key-cmp-fn)
			      (add-entry idx key1 val1))))
			 ((and (logbitp idx entries1) (logbitp idx subnodes2))
			  (let ((key1 val1 (ch-map-node-entry map-tree (1-bits-below idx entries1)))
				(subnode2 (ch-set-node-subnode set-tree (1-bits-below idx subnodes2))))
			    (when (set-contains? subnode2 key1)
			      (add-entry idx key1 val1))))
			 ((and (logbitp idx subnodes1) (logbitp idx entries2))
			  (let ((subnode1 (ch-map-node-subnode map-tree (1-bits-below idx subnodes1)))
				(key2 (ch-set-node-entry set-tree (1-bits-below idx entries2)))
				((val1? val1 (map-lookup subnode1 key2))))
			    (when val1?
			      (add-entry idx key2 val1))))
			 ((and (logbitp idx subnodes1) (logbitp idx subnodes2))
			  (add-subnode idx (rec (ch-map-node-subnode map-tree (1-bits-below idx subnodes1))
						(ch-map-node-subnode set-tree (1-bits-below idx subnodes2))
						(1+ depth))))))
		 (ch-map-compact-node res-n))))))))

(defun ch-map-tree-restrict-not (map-tree set-tree key-hash-fn key-cmp-fn val-hash-fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function key-hash-fn key-cmp-fn val-hash-fn))
  (rlabels (rec map-tree set-tree 0)
    (rec (map-tree set-tree depth)
      (declare (type (integer 0 64) depth))
      (cond ((or (null map-tree) (null set-tree)) nil)
	    ((and (consp map-tree) (consp set-tree))
	     (if (= (the fixnum (caar map-tree)) (the fixnum (car set-tree)))
		 (let ((result (wb-map-tree-restrict-not (cdr map-tree) (cdr set-tree) key-cmp-fn)))
		   (ch-map-node-from-wb result (car set-tree) depth))
	       map-tree))
	    ((consp map-tree)
	     (let ((result nil))
	       (do-wb-map-tree-pairs (k v (cdr map-tree))
		 (unless (ch-set-tree-contains? set-tree k key-hash-fn key-cmp-fn depth)
		   (setq result (wb-map-tree-with result k v key-cmp-fn (fn (_ _))))))
	       (ch-map-node-from-wb result (caar map-tree) depth)))
	    ((consp set-tree)
	     (do-wb-set-tree-members (k (cdr set-tree))
	       (setq map-tree (ch-map-tree-less map-tree k key-hash-fn key-cmp-fn val-hash-fn depth)))
	     map-tree)
	    (t
	     (let ((entries1 (ch-map-node-entry-mask map-tree))
		   (entries2 (ch-set-node-entry-mask set-tree))
		   (subnodes1 (ch-map-node-subnode-mask map-tree))
		   (subnodes2 (ch-set-node-subnode-mask set-tree))
		   ;; The result can be longer than `map-tree', because the restriction of two subnodes
		   ;; could be an entry.
		   ((res-len (+ ch-map-node-header-size
				(* 2 (+ (logcount entries1) (logcount subnodes1)))))
		    ((res-n (make-array res-len :initial-element 0)))))
	       (setf (ch-map-node-value-hash res-n) nil)
	       (flet ((add-entry (idx key val)
			(ch-map-node-add-entry res-n idx key val key-hash-fn))
		      (add-subnode (idx subnode)
			(ch-map-node-add-subnode res-n idx subnode key-hash-fn))
		      (map-subtree-less (subtree key)
			(ch-map-tree-less subtree key key-hash-fn key-cmp-fn val-hash-fn (1+ depth)))
		      (set-contains? (set-subtree key)
			(ch-set-tree-contains? set-subtree key key-hash-fn key-cmp-fn (1+ depth))))
		 (do-bit-indices (idx (logior entries1 subnodes1))
		   (cond ((logbitp idx entries1)
			  (let ((key1 val1 (ch-map-node-entry map-tree (1-bits-below idx entries1))))
			    (cond ((logbitp idx entries2)
				   (let ((key2 (ch-set-node-entry set-tree (1-bits-below idx entries2))))
				     (unless (equal?-cmp key1 key2 key-cmp-fn)
				       (add-entry idx key1 val1))))
				  ((logbitp idx subnodes2)
				   (let ((subnode2 (ch-set-node-subnode set-tree (1-bits-below idx subnodes2))))
				     (unless (set-contains? subnode2 key1)
				       (add-entry idx key1 val1))))
				  (t (add-entry idx key1 val1)))))
			 ((logbitp idx subnodes1)
			  (let ((subnode1 (ch-map-node-subnode map-tree (1-bits-below idx subnodes1))))
			    (cond ((logbitp idx entries2)
				   (let ((key2 (ch-set-node-entry set-tree (1-bits-below idx entries2))))
				     (add-subnode idx (map-subtree-less subnode1 key2))))
				  ((logbitp idx subnodes2)
				   (let ((subnode2 (ch-set-node-subnode set-tree (1-bits-below idx subnodes2))))
				     (add-subnode idx (rec subnode1 subnode2 (1+ depth)))))
				  (t (add-subnode idx subnode1)))))))
		 (ch-map-compact-node res-n))))))))

(defun ch-map-node-from-wb (wb-map-tree key-hash depth)
  (declare (optimize (speed 3) (safety 0)))
  (case (wb-map-tree-size wb-map-tree)
    (0 nil)
    (1 (let ((k v (wb-map-tree-arb-pair wb-map-tree)))
	 (vector (ash 1 (champ-hash-bits key-hash depth))
		 0 1 key-hash nil k v)))
    (t (cons (cons key-hash nil) wb-map-tree))))

(defun ch-map-compact-node (n)
  (declare (optimize (speed 3) (safety 0)))
  (let ((entries (ch-map-node-entry-mask n))
	(subnodes (ch-map-node-subnode-mask n)))
    (and (or (/= entries 0) (/= subnodes 0))
	 (let ((len (length (the simple-vector n)))
	       (n-entries (logcount entries))
	       ((extra (- len ch-map-node-header-size (* 2 n-entries) (logcount subnodes)))))
	   (when (< extra 0)
	     (error "Bug!  Not enough space allocated for ch-map-node"))
	   (if (= extra 0) n
	     (vector-remove-n-at n (+ ch-map-node-header-size (* 2 n-entries)) extra))))))

(defun ch-map-tree-compose (tree fn)
  (declare (optimize (speed 3) (safety 0))
	   (type function fn))
  (cond ((null tree) nil)
	((consp tree)
	 (wb-map-tree-compose tree fn))
	(t
	 (let ((n (make-array (length (the simple-vector tree)) :initial-element 0)))
	   (dotimes (i (logcount (ch-map-node-entry-mask tree)))
	     (let ((entry-idx (+ ch-map-node-header-size (* 2 i))))
	       (setf (svref n entry-idx) (svref tree entry-idx))
	       (setf (svref n (1+ entry-idx)) (funcall fn (svref tree (1+ entry-idx))))))
	   (dotimes (i (logcount (ch-map-node-subnode-mask tree)))
	     (let ((subnode-idx (- (length (the simple-vector tree)) i 1)))
	       (setf (svref n subnode-idx)
		     (ch-map-tree-compose (svref tree subnode-idx) fn))))
	   (setf (ch-map-node-entry-mask n) (ch-map-node-entry-mask tree))
	   (setf (ch-map-node-subnode-mask n) (ch-map-node-subnode-mask tree))
	   (setf (ch-map-node-size n) (ch-map-node-size tree))
	   (setf (ch-map-node-key-hash n) (ch-map-node-key-hash tree))
	   (setf (ch-map-node-value-hash n) nil)
	   n))))

(defun ch-map-tree-verify (tree key-hash-fn val-hash-fn)
  (or (null tree)
      (rlabels (rec tree 0 0)
	(rec (node depth partial-hash)
	  (macrolet ((test (form)
		       `(or ,form
			    (error "Test failed at ~:A: ~S" (path depth partial-hash) ',form))))
			    (progn
			      (cerror "Ignore and proceed."
				      "Verification check failed at ~:A: ~S" (path depth partial-hash) ',form)
			      nil))))
	    (let ((entry-mask (ch-map-node-entry-mask node))
		  (subnode-mask (ch-map-node-subnode-mask node))
		  ((entry-bits (bit-indices entry-mask))
@@ -1144,14 +2409,17 @@ (defun ch-map-tree-verify (tree)
		   (test (not (and (> depth 0) (= 0 entry-mask) (= 1 (logcount subnode-mask))
				   (consp (svref node (1- (length node)))))))
		   (let ((size (logcount entry-mask))
			 (content-hash 0))
			 (node-key-hash 0)
			 (node-value-hash 0))
		     (and
		       ;; Check entry key hashes
		       (gmap :and (fn (key-idx hash-bits)
				    (let ((key (svref node (+ ch-map-node-header-size (* 2 key-idx))))
					  ((key-hash (hash-value-fixnum key)))
					  ((key-hash (hash-to-fixnum key key-hash-fn)))
					  (value (svref node (+ ch-map-node-header-size (1+ (* 2 key-idx))))))
				      (setq content-hash (logxor content-hash key-hash (hash-value-fixnum value)))
				      (hash-mixf node-key-hash key-hash)
				      (when (ch-map-node-value-hash node)
					(hash-mixf node-value-hash (hash-to-fixnum value val-hash-fn)))
				      (test (= (ldb (byte (* champ-hash-bits-per-level (1+ depth)) 0)
						    key-hash)
					       (new-partial-hash hash-bits depth partial-hash)))))
@@ -1161,23 +2429,36 @@ (defun ch-map-tree-verify (tree)
		       (gmap :and (fn (subnode-idx hash-bits)
				    (let ((subnode (svref node (- (length node) 1 subnode-idx))))
				      (if (consp subnode)
					  (let ((chash 0))
					  (let ((key-hash (hash-to-fixnum (wb-map-tree-arb-pair (cdr subnode))
									  key-hash-fn))
						(vhash 0))
					    (test (consp (car subnode)))
					    (test (> (wb-map-tree-size (cdr subnode)) 1))
					    (do-wb-map-tree-pairs (k v (cdr subnode))
					      (setf chash (logxor chash (hash-value-fixnum k) (hash-value-fixnum v))))
					    (setf content-hash (logxor content-hash chash))
					      (let ((kh (hash-to-fixnum k key-hash-fn)))
						(test (= kh key-hash))
						(when (cdar subnode)
						  (hash-mixf vhash (hash-to-fixnum v val-hash-fn)))))
					    (hash-mixf node-key-hash key-hash)
					    (incf size (wb-map-tree-size (cdr subnode)))
					    (test (= (car subnode) chash)))
					    (when (cdar subnode)
					      (test (= (cdar subnode) vhash))
					      (hash-mixf node-value-hash vhash))
					    (test (= (caar subnode) key-hash)))
					(and (rec subnode (1+ depth) (new-partial-hash hash-bits depth partial-hash))
					     (progn
					       (incf size (ch-map-node-size subnode))
					       (setf content-hash
						     (logxor content-hash (ch-map-node-hash-value subnode)))
					       (hash-mixf node-key-hash (ch-map-node-key-hash subnode))
					       (when (ch-map-node-value-hash node)
						 (hash-mixf node-value-hash (ch-map-node-value-hash subnode)))
					       t)))))
			     (:arg index 0)
			     (:arg list subnode-bits))
		       ;; Finally, check size and hash
		       ;; Finally, check size and hashes
		       (test (= (ch-map-node-size node) size))
		       (test (= (ch-map-node-hash-value node) content-hash))))))))
		       (test (= (ch-map-node-key-hash node) node-key-hash))
		       (or (null (ch-map-node-value-hash node))
			   (test (= (ch-map-node-value-hash node) node-value-hash)))))))))
	(new-partial-hash (hash-bits depth partial-hash)
	  (dpb hash-bits (byte champ-hash-bits-per-level (* champ-hash-bits-per-level depth))
	       partial-hash))
@@ -1189,3 +2470,4 @@ (defun ch-map-tree-verify (tree)
		    path))
	    (nreverse path))))))

    
+7 −0
Changes for Code/complement-sets.lisp: 7 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -40,6 +40,8 @@ (defmethod complement ((cs complement-set))
  (complement-set-complement cs))

(defun full-set ()
  "The set containing everything.  It is a complement set, so it cannot be
enumerated, but certain other operations are defined on it."
  (make-complement-set (empty-set)))

(defmethod contains? ((cs complement-set) x &optional (y nil y?))
@@ -138,6 +140,11 @@ (defmethod compare ((cs complement-set) (s set))
(defmethod compare ((s set) (cs complement-set))
  ':less)

(defmethod hash-value ((cs complement-set))
  ;; Using one's complement instead of two's, so the full set has a different hash (-1)
  ;; from the empty set (0).
  (logxor -1 (hash-value-fixnum (complement-set-complement cs))))

(defmethod make-load-form ((cs complement-set) &optional environment)
  (declare (ignore environment))
  `(complement ',(complement-set-complement cs)))
+4 −4
Changes for Code/defs.lisp: 4 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -47,7 +47,7 @@ (defpackage :fset
	   #:equal? #:compare #:compare-slots #:compare-slots-no-unequal #:eql-compare
	   #:define-equality-slots #:define-comparison-slots #:define-hash-function
	   #:unwrap-equivalent-node ; custom comparison functions may have to call this
	   #:hash-value #:zero
	   #:hash-value #:hash-value-fixnum #:zero #:hash-mix #:hash-mixf #:hash-multiply
	   #:identity-equality-mixin #:identity-ordering-mixin
	   #:define-cross-type-compare-methods
	   #:compare-lexicographically
@@ -57,7 +57,7 @@ (defpackage :fset
	   #:empty-wb-set #:empty-wb-bag #:empty-wb-map #:empty-wb-seq
	   #:empty-dyn-tuple #:empty-ch-set #:empty-ch-map
	   #:empty-replay-set #:empty-wb-replay-set #:empty-replay-map #:empty-wb-replay-map
	   #:least #:greatest #:lookup #:rank #:at-rank #:at-index #:@
	   #:least #:greatest #:lookup #:rank #:at-rank #:index #:at-index #:@
	   #:with #:less #:split-from #:split-above #:split-through #:split-below
	   #:union #:bag-sum #:intersection #:bag-product #:complement
	   #:set-difference #:set-difference-2 #:bag-difference #:bag-pairs
@@ -166,7 +166,7 @@ (defpackage :fset2
	   #:equal? #:compare #:compare-slots #:compare-slots-no-unequal #:eql-compare
	   #:define-equality-slots #:define-comparison-slots #:define-hash-function
	   #:unwrap-equivalent-node ; custom comparison functions may have to call this
	   #:hash-value #:zero
	   #:hash-value #:hash-value-fixnum #:zero #:hash-mix #:hash-mixf #:hash-multiply
	   #:identity-equality-mixin #:identity-ordering-mixin
	   #:define-cross-type-compare-methods
	   #:compare-lexicographically
@@ -175,7 +175,7 @@ (defpackage :fset2
	   #:empty-set #:empty-bag #:empty-map #:empty-seq #:empty-tuple
	   #:empty-wb-set #:empty-wb-bag #:empty-wb-map #:empty-wb-seq
	   #:empty-dyn-tuple
	   #:least #:greatest #:lookup #:rank #:at-rank #:@
	   #:least #:greatest #:lookup #:rank #:at-rank #:index #:at-index #:@
	   #:with #:less #:split-from #:split-above #:split-through #:split-below
	   #:union #:bag-sum #:intersection #:bag-product #:complement
	   #:set-difference #:set-difference-2 #:bag-difference #:bag-pairs
+618 −109

File changed.

Preview size limit exceeded, changes collapsed.

+98 −22
Changes for Code/hash.lisp: 98 added lines, 22 removed lines.
Original line number Diff line number Diff line
@@ -9,56 +9,132 @@

(in-package :fset)

(defgeneric hash-value (x))
(defgeneric hash-value (x)
  (:documentation
    "Returns a fixnum providing an encoding of the contents of `x'.  The
result can be negative.  For best performance, it is recommended to use
fixnum arithmetic and return a fixnum; however, Common Lisp gives us no
way to enforce this constraint, so callers should use `hash-value-fixnum'
instead.

When writing methods for this generic function, in order to force fixnum
arithmetic, you may find `hash-mix', `hash-mixf', and `hash-multiply' useful.

This generic function is used in combination with `compare', so it is
important that for any two objects on which `compare' returns `:equal'
or `:unequal', this function returns the same hash value."))

(define-hash-function compare hash-value)

;;; As of this writing, these methods are tentative.  They should be gone over for performance
;;; and hash quality (well-distributed-ness) in the major Lisp implementations.
(declaim (inline hash-value-fixnum))
(defun hash-value-fixnum (x)
  "Returns the `hash-value' of `x', ensuring that the result is a fixnum."
  (let ((h (hash-value x)))
    (if (typep h 'fixnum) h
      (the fixnum (squash-bignum-hash h)))))

(defun squash-bignum-hash (h)
  (let ((len (integer-length h))
	(fixnum-len (integer-length most-positive-fixnum))
	(fh 0))
    (dotimes (i (ceiling len fixnum-len))
      (hash-mixf fh (ldb (byte fixnum-len (* fixnum-len i)) h)))
    (the fixnum (if (< h 0) (- fh) fh))))


(defmethod hash-value ((x identity-equality-mixin))
  ;; &&& Seems to work in SBCL
  (logxor (sxhash (class-of x)) (slot-value x 'serial-number)))
  (hash-mix (class-hash-value x) (slot-value x 'serial-number)))

(defmethod hash-value ((x identity-ordering-mixin))
  ;; &&& Seems to work in SBCL
  (logxor (sxhash (class-of x)) (slot-value x 'serial-number)))
  (hash-mix (class-hash-value x) (slot-value x 'serial-number)))

(defmethod hash-value ((s null))
  #32Rnil) ; = 24149.

(defmethod hash-value ((x real))
  (sxhash x))

(defmethod hash-value ((x fixnum))
  ;; Seems reasonable for our purposes
  ;; &&& Oops -- should strip sign bit?
  x)
(defmethod hash-value ((x integer))
  ;; It's fine if `x' is negative.
  (if (typep x 'fixnum) x
    (squash-bignum-hash x)))

(defmethod hash-value ((x complex))
  (sxhash x))

(defmethod hash-value ((x character))
  (sxhash x)) ; I guess
  (sxhash x))

(defmethod hash-value ((x symbol))
  ;; None of SBCL, CCL, Allegro, LispWorks, or CLASP include the package in the hash.  Of these,
  ;; only on SBCL is the hash of a symbol different from that of its `symbol-name'.
  (sxhash x))
  ;; None of SBCL, CCL, ABCL, Allegro, LispWorks, or CLASP include the package in the hash.  (Of these,
  ;; only on SBCL is the hash of a symbol different from that of its `symbol-name'.)  We _could_ mix
  ;; in the hash of the package, but how often does one really use symbols from multiple packages in
  ;; one set or map?  We'll leave that problem for `compare' — it handles it well.
  (symbol-hash-value x))

(defmethod hash-value ((x string))
  ;; We could, of course, do our own string hashing (using maybe SipHash? plenty to choose from:
  ;; https://en.wikipedia.org/wiki/List_of_hash_functions).  But the built-in string hash should
  ;; be well optimized for the implementation.  Let's go with it for now.
  (sxhash x))

(defmethod hash-value ((x list))
  (logxor (hash-value (car x)) (logand most-positive-fixnum (* 11 (hash-value (cdr x))))))
  ;; We assume that the list is longer (cdr-wise) than it is deep (car-wise).
  (list-hash-value x 4 12))

(defun list-hash-value (ls car-depth cdr-depth)
  ;; Since lists can be trees, they can have an arbitrary amount of stuff beneath them.
  ;; We bound the maximum depth to keep hashing effort from becoming excessive.
  (if (<= car-depth 0)
      0
    (do ((ls ls (cdr ls))
	 (result 0)
	 (mult 1 (hash-multiply mult 13))
	 (cdrs 0 (1+ cdrs)))
	((or (not (consp ls)) (>= cdrs cdr-depth))
	 (when (not (null ls))
	   (hash-mixf result (hash-value-fixnum ls))) ; defensive squashing
	 result)
      (let ((x (car ls))
	    ((x-hash (if (consp x)
			 (list-hash-value x (1- car-depth) (- cdr-depth 3))
		       (hash-value-fixnum x)))))
	(hash-mixf result (hash-multiply mult x-hash))))))

(defmethod hash-value ((x vector))
  (declare #+sbcl (sb-ext:muffle-conditions sb-ext:compiler-note))
  (if (simple-vector-p x)
      (do ((result 0 (logxor result (logand most-positive-fixnum (* mult (hash-value (svref x i))))))
	   (mult 1 (* mult 13))
      (do ((len (length x))
	   (i 0 (1+ i))
	   (len (length x)))
	   (mult 1 (hash-multiply mult 13))
	   (result 0 (hash-mix result (hash-multiply mult (hash-value-fixnum (svref x i))))))
	  ((= i len) result))
    (do ((result 0 (logxor result (logand most-positive-fixnum (* mult (hash-value (aref x i))))))
	 (mult 1 (* mult 13))
    (do ((len (length x))
	 (i 0 (1+ i))
	 (len (length x)))
	 (mult 1 (hash-multiply mult 13))
	 (result 0 (hash-mix result (hash-multiply mult (hash-value-fixnum (aref x i))))))
	((= i len) result))))

(defmethod hash-value ((x pathname))
  (sxhash x))

;;; Arrays (that aren't vectors)
(defmethod hash-value ((x array))
  (declare #+sbcl (sb-ext:muffle-conditions sb-ext:compiler-note))
  (do ((len (array-total-size x))
       (i 0 (1+ i))
       (mult 1 (hash-multiply mult 13))
       (result 0 (hash-mix result (hash-multiply mult (hash-value-fixnum (row-major-aref x i))))))
      ((= i len) result)))

;;; Fallback for generic sequences
(defmethod hash-value ((x sequence))
  (declare #+sbcl (sb-ext:muffle-conditions sb-ext:compiler-note))
  (do ((len (length x))
       (i 0 (1+ i))
       (mult 1 (hash-multiply mult 13))
       (result 0 (hash-mix result (hash-multiply mult (hash-value-fixnum (elt x i))))))
      ((= i len) result)))

(defun zero (x)
  (declare (ignore x))
Loading
Loading