1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189(* Sets of non-negative integers, represented as Patricia tries whose nodes
hoist the maximum key of their subtree, with a word-sized bitmap per key.
{2 Representation}
An element [x] is encoded as a key [x / w] and a bit [1 lsl (x mod w)],
where [w = Sys.word_size - 1] is the number of bits of an OCaml integer.
A set is a map from keys to non-zero bitmaps.
A tree is either [Empty] or a node with a key [k], the largest key of the
tree, its bitmap [v], and two children [l] and [r]. Let [m] be the most
significant bit of [k] ([m = 0] when [k = 0]). The other keys of the tree
are split as follows:
- [r] holds the keys that are less than [m];
- [l] holds the keys that are in the interval [\[m, k)], with their bit [m]
cleared: this is the "frame" of the left child.
Hence, every key of [r] is less than [m], and every key of [l] is less
than [k - m]. In particular, if [k] is a power of two, [l] is empty, and if
[k = 0], both children are empty. No node has an empty bitmap.
This representation is canonical: a set has exactly one representation,
so structural equality coincides with set equality. Each node stores data,
so a set with [n] distinct keys has exactly [n] nodes. The most significant
bit of the key strictly decreases along every path, so the depth of a tree
is bounded by the number of bits of a key.
The elements of a tree are enumerated in increasing order by visiting [r],
then [l], then the root. The key of a node is relative to its frame: the
absolute key is obtained by or-ing the most significant bits of the
ancestors at which a left branch was taken (the "prefix").
{2 Encoding of keys}
Every descent needs the most significant bit of the key of each node it
visits. Computing it costs a call to a C stub, so it is cached in the
node: the field [kk] holds the key in its low [kbits] bits and
[msb_index key + 1] (or [0] for the key [0]) in the bits above. Keys are
below [max_int / w], hence they fit in [kbits] bits, and the remaining
bits are enough for the index (see [kbits] below).
Empty trees are an immediate constructor rather than a sentinel node: the
garbage collector skips the empty children of the leaves instead of
following a pointer to the sentinel, which makes major collections
cheaper. *)(* The children are mutable only so that [Sharing.equal] and
[Sharing.compare] can replace a child with a structurally equal one. No
other operation mutates a tree. *)typet=|Empty|Nodeof{kk:int;v:int;mutablel:t;mutabler:t}typeelt=intletempty=Emptyletmsb=Bit_lib.extract_msbletlt_msb=Bit_lib.lt_msb(* -------------------------------------------------------------------------- *)(* Encoding of keys. *)(* Keys are below [max_int / w < 2^kbits] and the index of their most
significant bit, plus one, is at most [kbits]: it fits in the remaining
bits. With 63-bit integers, keys take 57 bits and the index 6 bits; with
32-bit (js_of_ocaml) or 31-bit integers, keys take 27 or 26 bits and the
index 5 bits. The index may use the sign bit: [kk] is never compared
directly, only through [key] and [mbit]. *)letkbits=Sys.int_size-(ifSys.int_size>32then6else5)letkmask=1lslkbits-1(* The key of an encoded key [kk]. *)let[@inline]keykk=kklandkmask(* The most significant bit of the key of [kk], without a C call. *)let[@inline]mbitkk=(1lsl(kklsrkbits))lsr1let[@inline]packik=klor(ilslkbits)let[@inline]indexkk=kklsrkbits(* [enc_index m] is the index stored for the keys whose most significant bit
is [m]. *)let[@inline]enc_indexm=ifm=0then0elseBit_lib.msb_indexm+1let[@inline]enck=ifk=0then0elsepack(Bit_lib.msb_indexk+1)k(* -------------------------------------------------------------------------- *)(* Encoding of elements. *)letword=Sys.word_size-1let[@inline]key_ofx=x/wordlet[@inline]bit_ofx=1lsl(xmodword)let[@inline]basek=k*word(* The least and greatest elements of the bitmap [v] at absolute key [k]. *)let[@inline]lowestkv=basek+Bit_lib.lsb_indexvlet[@inline]highestkv=basek+Bit_lib.msb_indexvletcheck_eltfnx=ifx<0theninvalid_arg("PatSet."^fn^": negative element")(* The bitmap and the left child of a tree, for the places where a tree is
known to be non-empty but is not destructured. *)let[@inline]bits=functionEmpty->0|Noden->n.vlet[@inline]left=functionEmpty->Empty|Noden->n.l(* -------------------------------------------------------------------------- *)(* Low-level operations on keys and bitmaps. *)let[@inline]leafkv=Node{kk=enck;v;l=Empty;r=Empty}(* [lookup k t] is the bitmap associated with key [k] in [t] ([0] if none). *)letreclookupk=function|Empty->0|Nodet->ifk>=keyt.kkthenifk=keyt.kkthent.velse0elseletm=mbitt.kkinifklandm<>0thenlookup(klxorm)t.lelselookupkt.r(* [push k v t] adds the key [k] with bitmap [v <> 0] to [t], where [k] is
greater than every key of [t]. The new key becomes the root and the old
root sinks into the left child if it shares the most significant bit. *)letrecpushkv=function|Empty->leafkv|Nodenast->letkk=enckinletm=mbitkkinifkeyn.kklandm<>0thenNode{kk;v;l=push(keyn.kklxorm)n.vn.l;r=n.r}elseNode{kk;v;l=Empty;r=t}(* [join kk l r] is the tree obtained by removing the root of a node with
encoded key [kk] and children [l] and [r]: the maximum of [l], if any, is
promoted. It has the same most significant bit as the removed root. *)letrecjoinkklr=matchlwith|Empty->r|Noden->Node{kk=pack(indexkk)(mbitkklorkeyn.kk);v=n.v;l=joinn.kkn.ln.r;r}(* [rebuild t tkk tv tl tr v l r], where [t] is the node
[{kk = tkk; v = tv; l = tl; r = tr}], is the node [t] with new bitmap [v]
and children [l] and [r], reusing [t] when nothing changed, and removing
the root if [v = 0]. *)let[@inline]rebuildttkktvtltrvlr=ifv=0thenjointkklrelseifv=tv&&l==tl&&r==trthentelseNode{kk=tkk;v;l;r}(* [add_bits k v t] adds the bits [v <> 0] at key [k]. *)letrecadd_bitskv=function|Empty->leafkv|Nodenast->ifk>=keyn.kkthenifk=keyn.kkthenletv'=n.vlorvinifv'=n.vthentelseNode{nwithv=v'}elsepushkvtelseletm=mbitn.kkinifklandm<>0thenletl=add_bits(klxorm)vn.linifl==n.lthentelseNode{nwithl}elseletr=add_bitskvn.rinifr==n.rthentelseNode{nwithr}(* [remove_bits k v t] removes the bits [v] at key [k]. *)letrecremove_bitskv=function|Empty->Empty|Nodenast->ifk>=keyn.kkthenifk=keyn.kkthenletv'=n.vlandlnotvinifv'=n.vthentelseifv'=0thenjoinn.kkn.ln.relseNode{nwithv=v'}elsetelseletm=mbitn.kkinifklandm<>0thenletl=remove_bits(klxorm)vn.linifl==n.lthentelseNode{nwithl}elseletr=remove_bitskvn.rinifr==n.rthentelseNode{nwithr}(* -------------------------------------------------------------------------- *)(* Elementary operations. *)letis_emptyt=t==Emptyletis_singleton=function|Node{v;l=Empty;r=Empty;_}->vland(v-1)=0|_->falseletsingletonx=check_elt"singleton"x;leaf(key_ofx)(bit_ofx)letaddxt=check_elt"add"x;add_bits(key_ofx)(bit_ofx)tletremovext=ifx<0thentelseremove_bits(key_ofx)(bit_ofx)tletmemxt=x>=0&&lookup(key_ofx)tlandbit_ofx<>0letcardinalt=letreclooptacc=matchtwith|Empty->acc|Noden->loopn.r(loopn.l(acc+Bit_lib.pop_countn.v))inloopt0(* -------------------------------------------------------------------------- *)(* Minimum and maximum. *)(* [min_in pre t] is the least element of the non-empty tree [t], whose keys
are relative to the prefix [pre]. *)letrecmin_inpre=function|Empty->raiseNot_found|Noden->matchn.rwith|Node_asr->min_inprer|Empty->matchn.lwith|Node_asl->min_in(prelormbitn.kk)l|Empty->lowest(prelorkeyn.kk)n.vletminimumt=min_in0tletmaximum=function|Empty->raiseNot_found|Noden->highest(keyn.kk)n.v(* The maximum is at the root, hence cheaper than the minimum. *)letchoose=maximumletmin_elt_optt=ift==EmptythenNoneelseSome(min_in0t)letmax_elt_opt=function|Empty->None|Noden->Some(highest(keyn.kk)n.v)letcompare_minimumab=matcha,bwith|Empty,Empty->0|Empty,_->-1|_,Empty->1|_->Int.compare(min_in0a)(min_in0b)(* -------------------------------------------------------------------------- *)(* Carried keys.
When two trees whose roots share their most significant bit [m] are
merged, the smaller root moves into the upper half of the result, where it
must be merged with the left child of the other tree. Rather than building
this "pennant" (the root minus [m], followed by the left child), we carry
it into the recursion: [union_push] and [diff_push] handle a single
carried key. When a second key must be carried, we switch to "virtual
trees", which describe any number of carried keys without allocating.
Carried keys always form a segment of a left spine of an input tree. In
the current frame, whose keys are below some power of two [bound], the key
of a carried node [c] is [key c.kk land (bound - 1)]: the bits of its key
above [bound] are exactly those stripped since [c] was carried. We write
[mk] for [bound - 1]; it is shared by both operands.
A virtual tree is described by three values [h s p]:
- the chain: the nodes [h], [h.l], [h.l.l], ..., up to [s] excluded, which
stand for the keys [key c.kk land mk] with the bitmaps [c.v], in
decreasing order;
- the tail: [s] if [p], [Empty] otherwise; its keys are below those of the
chain. A plain tree [t] is the virtual tree [t t true].
Splitting a virtual tree at the bit [m] (when every key is below [2m])
yields an upper and a lower virtual tree, again without allocation: the
chain keys that have the bit [m] are a prefix of the chain; the others,
followed by the tail, form the lower part. If every chain key has the bit
[m], the root of the tail may join the chain, in which case its left child
becomes the new tail and its right child goes to the lower part. Both
parts use the mask [m - 1]. *)(* [vmax h s p mk] is the largest key of a virtual tree, or [-1] if it is
empty. The corresponding bitmap is [bits h]. *)let[@inline]vmaxhspmk=matchhwith|Nodenwhenh!=s->keyn.kklandmk|_->ifpthenmatchswithNoden->keyn.kk|Empty->-1else-1let[@inline]vtailsp=ifpthenselseEmpty(* [materialize h s p mk] builds a virtual tree. *)letrecmaterializehspmk=matchhwith|Nodenwhenh!=s->push(keyn.kklandmk)n.v(materializen.lspmk)|_->vtailsp(* [first_low m c s] is the first node of the chain [c .. s] whose key does
not have the bit [m], or [s] if there is none. *)letrecfirst_lowmcs=matchcwith|Nodenwhenc!=s&&keyn.kklandm<>0->first_lowmn.ls|_->c(* -------------------------------------------------------------------------- *)(* Comparisons. *)letrecequalab=a==b||matcha,bwith|Nodea,Nodeb->a.kk=b.kk&&a.v=b.v&&equala.lb.l&&equala.rb.r|_->false(* A structural total order (it is not the lexicographic order on sorted
sequences of elements). *)letreccompareab=ifa==bthen0elsematcha,bwith|Empty,_->-1|_,Empty->1|Nodea,Nodeb->letc=Int.compare(keya.kk)(keyb.kk)inifc<>0thencelseletc=Int.comparea.vb.vinifc<>0thencelseletc=comparea.lb.linifc<>0thencelsecomparea.rb.r(* Comparisons that, as a side effect, make structurally equal subtrees of
their arguments physically equal. This speeds up later comparisons and
lets the garbage collector reclaim duplicates. Since the representation is
canonical, a subtree can be replaced with any structurally equal one.
The copy to keep is chosen by [Bit_lib.share_choose], a C stub that
prefers a value outside the minor heap (so that unification creates no
major-to-minor pointers and the young copy can be collected early), and
otherwise the one at the higher address. Concurrent use from several
domains is safe: a racing reader sees either child, and both are equal. *)moduleSharing=structletrecequalab=a==b||matcha,bwith|Nodea,Nodeb->a.kk=b.kk&&a.v=b.v&&(a.l==b.l||(equala.lb.l&&(ifBit_lib.share_choosea.lb.l==a.lthenb.l<-a.lelsea.l<-b.l;true)))&&(a.r==b.r||(equala.rb.r&&(ifBit_lib.share_choosea.rb.r==a.rthenb.r<-a.relsea.r<-b.r;true)))|_->falseletreccompareab=ifa==bthen0elsematcha,bwith|Empty,_->-1|_,Empty->1|Nodea,Nodeb->letc=Int.compare(keya.kk)(keyb.kk)inifc<>0thencelseletc=Int.comparea.vb.vinifc<>0thencelseletc=ifa.l==b.lthen0elsecomparea.lb.linifc<>0thencelsebeginifa.l!=b.lthen(ifBit_lib.share_choosea.lb.l==a.lthenb.l<-a.lelsea.l<-b.l);letc=ifa.r==b.rthen0elsecomparea.rb.rinifc=0&&a.r!=b.rthen(ifBit_lib.share_choosea.rb.r==a.rthenb.r<-a.relsea.r<-b.r);cendend(* The root of the larger tree is irrelevant to [subset] and [disjoint]; the
root of the smaller one is looked up in the other tree. Carrying it into the
recursion instead, as [union] does, avoids this second descent but makes
every step along its path more expensive: measured, it is slower. *)letrecsubsetab=a==b||matcha,bwith|Empty,_->true|_,Empty->false|Nodena,Nodenb->letka=keyna.kkandkb=keynb.kkinifka=kbthenna.vlandlnotnb.v=0&&subsetna.lnb.l&&subsetna.rnb.relseifka>kbthenfalse(* the maximum of [a] is not in [b] *)elseiflt_msbkakbthensubsetanb.relse(* Same most significant bit [m], [ka < kb]: the root of [a] is looked
up in [b.l]; the root of [b] is irrelevant. *)letm=mbitnb.kkinna.vlandlnot(lookup(kalxorm)nb.l)=0&&subsetna.lnb.l&&subsetna.rnb.rletrecdisjointab=matcha,bwith|Empty,_|_,Empty->true|Nodena,Nodenb->a!=b&&letka=keyna.kkandkb=keynb.kkinifka=kbthenna.vlandnb.v=0&&disjointna.lnb.l&&disjointna.rnb.relseiflt_msbkakbthendisjointanb.relseiflt_msbkbkathendisjointna.rbelseifka<kbthenna.vlandlookup(kalxormbitnb.kk)nb.l=0&&disjointna.lnb.l&&disjointna.rnb.relsenb.vlandlookup(kblxormbitna.kk)na.l=0&&disjointna.lnb.l&&disjointna.rnb.r(* Under the precondition [a ⊆ b ∨ a ∩ b = ∅], it suffices to test one
element of [a]: its maximum is at the root. *)letquick_subsetab=matchawith|Empty->false|Noden->lookup(keyn.kk)blandn.v<>0(* -------------------------------------------------------------------------- *)(* Union. *)(* Physical equality: if the result of [union a b] is equal to [b], then [b]
is returned. (The same holds for [a] as long as [a] and [b] do not have
structurally equal but physically distinct subtrees.) *)letrecunionab=ifa==bthenbelsematcha,bwith|Empty,_->b|_,Empty->a|Nodena,Nodenb->letka=keyna.kkandkb=keynb.kkinifka=kbthenletl=unionna.lnb.linletr=unionna.rnb.rinletv=na.vlornb.vinifv=nb.v&&l==nb.l&&r==nb.rthenbelseifv=na.v&&l==na.l&&r==na.rthenaelseNode{kk=na.kk;v;l;r}elseiflt_msbkakbthen(* [a] lies below the most significant bit of [kb]. *)letr=unionanb.rinifr==nb.rthenbelseNode{nbwithr}elseiflt_msbkbkathenletr=unionna.rbinifr==na.rthenaelseNode{nawithr}else(* Same most significant bit [m]: the smaller root is carried into the
upper half. *)letm=mbitna.kkinletr=unionna.rnb.rinifka>kbthenletl=union_pushfalsena.lbnb.vnb.l(kblxorm)inifl==na.l&&r==na.rthenaelseNode{nawithl;r}elseletl=union_pushtruenb.lana.vna.l(kalxorm)inifl==nb.l&&r==nb.rthenbelseNode{nbwithl;r}(* [union_o xb x y] is the union of [x] and [y], where [xb] tells whether [x]
comes from the side whose physical identity is preserved. *)andunion_oxbxy=ifxbthenunionyxelseunionxy(* [union_push xb x h v y k] is the union of the tree [x] and the "pennant"
made of the carried node [h], standing for the key [k] (greater than every
key of [y]) with the bitmap [v], followed by its left child [y]. If the
result is equal to [x], then [x] is returned. *)andunion_pushxbxhvyk=matchxwith|Empty->pushkvy|Nodexn->letkx=keyxn.kkinifkx=kthenletm=mbitxn.kkinletl,r=matchywith|Nodeynwhenkeyyn.kklandm<>0->union_pushxbxn.lyyn.vyn.l(keyyn.kklxorm),union_oxbxn.ryn.r|_->xn.l,union_oxbxn.ryinletv'=xn.vlorvinifv'=xn.v&&l==xn.l&&r==xn.rthenxelseNode{xnwithv=v';l;r}elseiflt_msbkxkthen(* [x] lies in the lower half of the result. *)letkk=enckinletm=mbitkkinmatchywith|Nodeynwhenkeyyn.kklandm<>0->Node{kk;v;l=push(keyyn.kklxorm)yn.vyn.l;r=union_oxbxyn.r}|_->Node{kk;v;l=Empty;r=union_oxbxy}elseiflt_msbkkxthenletr=union_pushxbxn.rhvykinifr==xn.rthenxelseNode{xnwithr}else(* Same most significant bit [m], [k <> kx]. *)letm=mbitxn.kkinmatchywith|Nodeynwhenkeyyn.kklandm<>0->letr=union_oxbxn.ryn.rinifkx>kthen(* Both [k] and the root of [y] are carried into the upper half. *)letl=ifxbthenvunionhyn.ltruexn.lxn.ltrue(m-1)elsevunionxn.lxn.ltruehyn.ltrue(m-1)inifl==xn.l&&r==xn.rthenxelseNode{xnwithl;r}else(* [kx < k]: the upper halves are the pennants of [x] and [y]. *)letl=ifxbthenvunionyyn.ltruexxn.ltrue(m-1)elsevunionxxn.ltrueyyn.ltrue(m-1)inNode{kk=pack(indexxn.kk)k;v;l;r}|_->letr=union_oxbxn.ryinifkx>kthenletl=add_bits(klxorm)vxn.linifl==xn.l&&r==xn.rthenxelseNode{xnwithl;r}elseNode{kk=pack(indexxn.kk)k;v;l=push(kxlxorm)xn.vxn.l;r}(* [vunion ha sa pa hb sb pb mk] is the union of two virtual trees. If the
result is equal to an argument that is a plain tree, this argument is
returned (preferably the second one). *)andvunionhasapahbsbpbmk=ifha==sathenifhb==sbthenunion(vtailsapa)(vtailsbpb)elsematchhbwith|Nodenwhenn.l==sb->(* A single carried key, possibly followed by its left child. *)ifpbthenunion_pushfalse(vtailsapa)hbn.vn.l(keyn.kklandmk)elseadd_bits(keyn.kklandmk)n.v(vtailsapa)|_->vunion_genhasapahbsbpbmkelsematchhawith|Nodenwhenhb==sb&&n.l==sa->ifpathenunion_pushtrue(vtailsbpb)han.vn.l(keyn.kklandmk)elseadd_bits(keyn.kklandmk)n.v(vtailsbpb)|_->vunion_genhasapahbsbpbmkandvunion_genhasapahbsbpbmk=letka=vmaxhasapamkandkb=vmaxhbsbpbmkinifka<0thenmaterializehbsbpbmkelseifkb<0thenmaterializehasapamkelseiflt_msbkakbthenvunion_belowhasapahbsbpbmkkbfalseelseiflt_msbkbkathenvunion_belowhbsbpbhasapamkkatrueelsevunion_samehasapahbsbpbkakb(* [vunion_below] handles the case where [x] lies below the most significant
bit [m] of the maximum [ky] of [y]: the result has the root of [y], the
upper half of [y], and the union of [x] with the lower half of [y]. The
flag [sw] tells whether [x] is the second argument of [vunion]. *)andvunion_belowhxsxpxhysypymkkysw=matchhywith|Empty->assertfalse|Nodehyn->ifhy==sythen(* [y] is a plain tree. *)letr=ifswthenvunionhyn.rhyn.rtruehxsxpxmkelsevunionhxsxpxhyn.rhyn.rtruemkinifr==hyn.rthenhyelseNode{hynwithr}elseletm=msbkyinletmk=m-1inleth=hyn.linletc=first_lowmhsyinletl,r=ifc!=sythenmaterializehcfalsemk,(ifswthenvunioncsypyhxsxpxmkelsevunionhxsxpxcsypymk)elsematchsywith|Nodesynwhenpy&&keysyn.kklandm<>0->(* The root of the tail joins the chain. *)materializehsyn.ltruemk,(lett=syn.rinifswthenvuniontttruehxsxpxmkelsevunionhxsxpxtttruemk)|_->materializehcfalsemk,(lett=vtailsypyinifswthenvuniontttruehxsxpxmkelsevunionhxsxpxtttruemk)inNode{kk=pack(enc_indexm)ky;v=hyn.v;l;r}(* [vunion_same] handles the case where the maxima [ka] and [kb] of [a] and
[b] have the same most significant bit [m]. The largest maximum (or both,
if they are equal) becomes the root. Both virtual trees are split at [m]:
the upper halves are merged into the left child, and the lower halves
into the right child. *)andvunion_samehasapahbsbpbkakb=letk=ifka>kbthenkaelsekbinletm=msbkinletkk=pack(enc_indexm)kin(* Split [a] into [uha usa upa] and [lha lsa lpa]. If [ka = k], its
maximum is popped first. *)letuha,usa,upa,lha,lsa,lpa=matchsawith|Nodenwhenka=k&&ha==sa->(* Popping the root of a plain tree yields its two children. *)n.l,n.l,true,n.r,n.r,true|_->leth=ifka=kthenlefthaelsehainletc=first_lowmhsainifc!=sathenh,c,false,c,sa,paelsematchsawith|Nodenwhenpa&&keyn.kklandm<>0->h,n.l,true,n.r,n.r,true|_->h,sa,false,sa,sa,painletuhb,usb,upb,lhb,lsb,lpb=matchsbwith|Nodenwhenkb=k&&hb==sb->n.l,n.l,true,n.r,n.r,true|_->leth=ifkb=kthenlefthbelsehbinletc=first_lowmhsbinifc!=sbthenh,c,false,c,sb,pbelsematchsbwith|Nodenwhenpb&&keyn.kklandm<>0->h,n.l,true,n.r,n.r,true|_->h,sb,false,sb,sb,pbinletv=ifka=kbthenbitshalorbitshbelseifka=kthenbitshaelsebitshbinletl=vunionuhausaupauhbusbupb(m-1)inletr=vunionlhalsalpalhblsblpb(m-1)inmatchsb,sawith|Noden,_whenkb=k&&hb==sb&&v=n.v&&l==n.l&&r==n.r->sb|_,Nodenwhenka=k&&ha==sa&&v=n.v&&l==n.l&&r==n.r->sa|_->Node{kk;v;l;r}(* -------------------------------------------------------------------------- *)(* Intersection. *)(* If the result of [inter a b] is equal to [a], then [a] is returned. *)letrecinterab=ifa==bthenaelsematcha,bwith|Empty,_|_,Empty->Empty|Nodena,Nodenb->letka=keyna.kkandkb=keynb.kkinifka=kbthenletl=interna.lnb.linletr=interna.rnb.rinletv=na.vlandnb.vinifv=0thenjoinna.kklrelseifv=na.v&&l==na.l&&r==na.rthenaelseifv=nb.v&&l==nb.l&&r==nb.rthenbelseNode{kk=na.kk;v;l;r}elseiflt_msbkakbtheninteranb.relseiflt_msbkbkatheninterna.rb(* Same most significant bit: the larger root is not in the other tree,
and the maximum of the result is at most the smaller root. *)elseifka<kbthenletl=interna.lnb.linletr=interna.rnb.rinrebuildana.kkna.vna.lna.r(na.vlandlookup(kalxormbitnb.kk)nb.l)lrelseletl=internb.lna.linletr=internb.rna.rinrebuildbnb.kknb.vnb.lnb.r(nb.vlandlookup(kblxormbitna.kk)na.l)lr(* -------------------------------------------------------------------------- *)(* Difference. *)(* If the result of [diff a b] is equal to [a], then [a] is returned. *)letrecdiffab=ifa==bthenEmptyelsematcha,bwith|Empty,_->Empty|_,Empty->a|Nodena,Nodenb->letka=keyna.kkandkb=keynb.kkinifka=kbthenletl=diffna.lnb.linletr=diffna.rnb.rinrebuildana.kkna.vna.lna.r(na.vlandlnotnb.v)lrelseiflt_msbkakbthendiffanb.relseiflt_msbkbkathenletr=diffna.rbinifr==na.rthenaelseNode{nawithr}elseletm=mbitna.kkinletr=diffna.rnb.rinifka>kbthen(* The root of [a] survives; the root of [b] is carried. *)letl=diff_pushna.lbnb.vnb.l(kblxorm)inifl==na.l&&r==na.rthenaelseNode{nawithl;r}elseletl=diffna.lnb.linrebuildana.kkna.vna.lna.r(na.vlandlnot(lookup(kalxorm)nb.l))lr(* [diff_push x h hv y k] is the difference between [x] and the pennant made
of the carried node [h], standing for the key [k] with the bitmap [hv],
followed by its left child [y]. *)anddiff_pushxhhvyk=matchxwith|Empty->x|Nodexn->letkx=keyxn.kkinifkx=kthenletm=mbitxn.kkinletl,r=matchywith|Nodeynwhenkeyyn.kklandm<>0->diff_pushxn.lyyn.vyn.l(keyyn.kklxorm),diffxn.ryn.r|_->xn.l,diffxn.ryinrebuildxxn.kkxn.vxn.lxn.r(xn.vlandlnothv)lrelseiflt_msbkxkthen(* [x] lies in the lower half of the pennant. *)letm=msbkinmatchywith|Nodeynwhenkeyyn.kklandm<>0->diffxyn.r|_->diffxyelseiflt_msbkkxthenletr=diff_pushxn.rhhvykinifr==xn.rthenxelseNode{xnwithr}elseifkx<kthen(* The carried key is above every key of [x]: drop it. *)diffxyelseletm=mbitxn.kkinletl,r=matchywith|Nodeynwhenkeyyn.kklandm<>0->vdiffxn.lhyn.ltrue(m-1),diffxn.ryn.r|_->remove_bits(klxorm)hvxn.l,diffxn.ryinifl==xn.l&&r==xn.rthenxelseNode{xnwithl;r}(* [vdiff x hb sb pb mk] is the difference between the tree [x] and a
virtual tree. If nothing is removed, [x] is returned. *)andvdiffxhbsbpbmk=ifhb==sbthendiffx(vtailsbpb)elsematchhbwith|Empty->assertfalse|Nodehbn->ifhbn.l==sbthenifpbthendiff_pushxhbhbn.vhbn.l(keyhbn.kklandmk)elseremove_bits(keyhbn.kklandmk)hbn.vxelsematchxwith|Empty->x|Nodexn->letkb=keyhbn.kklandmkandkx=keyxn.kkinifkx=kbthenletm=mbitxn.kkinleth=hbn.linletc=first_lowmhsbinletl,r=ifc!=sbthenvdiffxn.lhcfalse(m-1),vdiffxn.rcsbpb(m-1)elsematchsbwith|Nodesbnwhenpb&&keysbn.kklandm<>0->vdiffxn.lhsbn.ltrue(m-1),diffxn.rsbn.r|_->vdiffxn.lhsbfalse(m-1),diffxn.r(vtailsbpb)inrebuildxxn.kkxn.vxn.lxn.r(xn.vlandlnothbn.v)lrelseiflt_msbkxkbthen(* [x] lies below the most significant bit [m] of [kb]: only the
lower half of [b] matters. *)letm=msbkbinletc=first_lowmhbsbinifc!=sbthenvdiffxcsbpb(m-1)elsematchsbwith|Nodesbnwhenpb&&keysbn.kklandm<>0->diffxsbn.r|_->diffx(vtailsbpb)elseiflt_msbkbkxthenletr=vdiffxn.rhbsbpbmkinifr==xn.rthenxelseNode{xnwithr}elseifkx<kbthen(* The maximum of [b] is above every key of [x]: drop it. *)vdiffxhbn.lsbpbmkelse(* [kx > kb], same most significant bit [m]: the root of [x]
survives. *)letm=mbitxn.kkinletc=first_lowmhbsbinletl,r=ifc!=sbthenvdiffxn.lhbcfalse(m-1),vdiffxn.rcsbpb(m-1)elsematchsbwith|Nodesbnwhenpb&&keysbn.kklandm<>0->vdiffxn.lhbsbn.ltrue(m-1),diffxn.rsbn.r|_->vdiffxn.lhbsbfalse(m-1),diffxn.r(vtailsbpb)inifl==xn.l&&r==xn.rthenxelseNode{xnwithl;r}(* -------------------------------------------------------------------------- *)(* Iteration. *)let[@inline]iter_bitsfkv=letb=basekinletv=refvinwhile!v<>0doleti=Bit_lib.lsb_index!vinv:=!vland(!v-1);f(b+i)donelet[@inline]rev_iter_bitsfkv=letb=basekinletv=refvinwhile!v<>0doleti=Bit_lib.msb_index!vinv:=!vlxor(1lsli);f(b+i)doneletreciterfpre=function|Empty->()|Nodet->iterfpret.r;iterf(prelormbitt.kk)t.l;iter_bitsf(prelorkeyt.kk)t.vletiterft=iterf0tletrecrev_iterfpre=function|Empty->()|Nodet->rev_iter_bitsf(prelorkeyt.kk)t.v;rev_iterf(prelormbitt.kk)t.l;rev_iterfpret.rletrev_iterft=rev_iterf0tletrecfoldfpretacc=matchtwith|Empty->acc|Nodet->letacc=foldfpret.raccinletacc=foldf(prelormbitt.kk)t.laccinletb=base(prelorkeyt.kk)inletv=reft.vandacc=refaccinwhile!v<>0doleti=Bit_lib.lsb_index!vinv:=!vland(!v-1);acc:=f(b+i)!accdone;!accletfoldftacc=foldf0taccletrecfold_rightfpretacc=matchtwith|Empty->acc|Nodet->letb=base(prelorkeyt.kk)inletv=reft.vandacc=refaccinwhile!v<>0doleti=Bit_lib.msb_index!vinv:=!vlxor(1lsli);acc:=f(b+i)!accdone;letacc=fold_rightf(prelormbitt.kk)t.l!accinfold_rightfpret.racc(* The elements in increasing order. *)letelementst=fold_right(funxxs->x::xs)0t[](* [find_bits p k v] is the least element of the bitmap [v] at key [k] that
satisfies [p], or [-1]. *)letfind_bitspkv=letb=basekinletrecloopv=ifv=0then-1elseletx=b+Bit_lib.lsb_indexvinifpxthenxelseloop(vland(v-1))inloopvletrecfind_firstppre=function|Empty->-1|Nodet->letx=find_firstppret.rinifx>=0thenxelseletx=find_firstp(prelormbitt.kk)t.linifx>=0thenxelsefind_bitsp(prelorkeyt.kk)t.vletfind_first_optpt=letx=find_firstp0tinifx<0thenNoneelseSomexletrecfor_allppre=function|Empty->true|Nodet->for_allppret.r&&for_allp(prelormbitt.kk)t.l&&find_bits(funx->not(px))(prelorkeyt.kk)t.v<0letfor_allpt=for_allp0tletexistspt=find_firstp0t>=0(* [filter_bits p k v] is the sub-bitmap of [v] whose elements satisfy [p].
The predicate is applied in increasing order. *)letfilter_bitspkv=letb=basekinletrecloopvacc=ifv=0thenaccelseleti=Bit_lib.lsb_indexvinletv=vland(v-1)inloopv(ifp(b+i)thenacclor(1lsli)elseacc)inloopv0letrecfilterppret=matchtwith|Empty->t|Noden->letr=filterppren.rinletl=filterp(prelormbitn.kk)n.linrebuildtn.kkn.vn.ln.r(filter_bitsp(prelorkeyn.kk)n.v)lrletfilterpt=filterp0tletpartitionpt=letyes=filterptinyes,difftyes(* -------------------------------------------------------------------------- *)(* Sequences and lists. *)typeenum=|End|Treeofint*t*enum(* a prefix and a tree *)|Bitsofint*int*enum(* an absolute key and a non-empty bitmap *)letrecseq_of_enume()=matchewith|End->Seq.Nil|Tree(_,Empty,e)->seq_of_enume()|Tree(pre,Nodet,e)->seq_of_enum(Tree(pre,t.r,Tree(prelormbitt.kk,t.l,Bits(prelorkeyt.kk,t.v,e))))()|Bits(k,v,e)->leti=Bit_lib.lsb_indexvinletv=vland(v-1)inSeq.Cons(basek+i,seq_of_enum(ifv=0theneelseBits(k,v,e)))letto_seqt=seq_of_enum(Tree(0,t,End))letadd_seqst=Seq.fold_left(funtx->addxt)tsletof_seqs=add_seqsemptyletof_listxs=List.fold_left(funtx->addxt)emptyxs(* -------------------------------------------------------------------------- *)(* Splitting. *)(* [above_bits k mask t] keeps the keys greater than [k], plus the bits
[mask] of key [k]. *)letrecabove_bitskmaskt=matchtwith|Empty->Empty|Noden->ifkeyn.kk<kthenEmptyelseifkeyn.kk=kthenletv=n.vlandmaskinifv=0thenEmptyelseifv=n.v&&n.l==Empty&&n.r==Emptythentelseleafkvelseletm=mbitn.kkinifklandm<>0thenletl=above_bits(klxorm)maskn.linifl==n.l&&n.r==EmptythentelseNode{nwithl;r=Empty}elseletr=above_bitskmaskn.rinifr==n.rthentelseNode{nwithr}(* [below_bits k mask t] keeps the keys smaller than [k], plus the bits
[mask] of key [k]. *)letrecbelow_bitskmaskt=matchtwith|Empty->t|Noden->ifkeyn.kk<kthentelseifkeyn.kk=kthenrebuildtn.kkn.vn.ln.r(n.vlandmask)n.ln.relseletm=mbitn.kkinifklandm<>0thenjoinn.kk(below_bits(klxorm)maskn.l)n.relsebelow_bitskmaskn.r(* Masks selecting the bits strictly above / below / at most / at least the
bit [b] (a power of two). *)let[@inline]bits_gtb=-blsl1let[@inline]bits_geb=-blet[@inline]bits_ltb=b-1let[@inline]bits_leb=blor(b-1)letabovext=ifx<0thentelseabove_bits(key_ofx)(bits_gt(bit_ofx))tletbelowxt=ifx<=0thenemptyelsebelow_bits(key_ofx)(bits_lt(bit_ofx))tletat_leastxt=ifx<=0thentelseabove_bits(key_ofx)(bits_ge(bit_ofx))tletat_mostxt=ifx<0thenemptyelsebelow_bits(key_ofx)(bits_le(bit_ofx))tletsplitxt=belowxt,memxt,abovext(* -------------------------------------------------------------------------- *)(* Decomposition. *)letsorted_unionss=List.fold_left(funaccs->unionaccs)emptyssletextract_unique_prefixs1s2=letx=minimums2inbelowxs1,at_leastxs1letextract_unique_suffixs1s2=letx=maximums2inabovexs1,at_mostxs1(* [max_sym_diff a b] is the greatest element of the symmetric difference of
[a] and [b], or [-1] if they are equal. Since the maximum of a tree is at
its root, the first mismatching root decides. *)letrecmax_sym_diffpreab=ifa==bthen-1elsematcha,bwith|Empty,Empty->-1|Nodena,Empty->highest(prelorkeyna.kk)na.v|Empty,Nodenb->highest(prelorkeynb.kk)nb.v|Nodena,Nodenb->letka=keyna.kkandkb=keynb.kkinifka<>kbthenifka>kbthenhighest(prelorka)na.velsehighest(prelorkb)nb.velseifna.v<>nb.vthenhighest(prelorka)(na.vlxornb.v)elseletd=max_sym_diff(prelormbitna.kk)na.lnb.linifd>=0thendelsemax_sym_diffprena.rnb.rletextract_shared_suffixs1s2=letx=max_sym_diff0s1s2inifx<0thens1,(empty,empty)elseabovexs1,(at_mostxs1,at_mostxs2)(* [min_gt pre k t] is the least element of [t] whose key is greater than
[k], or [-1]. *)letrecmin_gtprek=function|Empty->-1|Noden->ifkeyn.kk<=kthen-1elseletm=mbitn.kkinletx=ifklandm<>0thenmin_gt(prelorm)(klxorm)n.lelseletx=min_gtprekn.rinifx>=0||n.l==Emptythenxelsemin_in(prelorm)n.linifx>=0thenxelselowest(prelorkeyn.kk)n.v(* [min_sym_diff pre a b] is the least element of the symmetric difference
of [a] and [b], or [-1] if they are equal. *)letrecmin_sym_diffpreab=ifa==bthen-1elsematcha,bwith|Empty,_->min_inpreb|_,Empty->min_inprea|Nodena,Nodenb->letka=keyna.kkandkb=keynb.kkinifka=kbthenletx=min_sym_diffprena.rnb.rinifx>=0thenxelseletx=min_sym_diff(prelormbitna.kk)na.lnb.linifx>=0thenxelseletd=na.vlxornb.vinifd=0then-1elselowest(prelorka)delseiflt_msbkakbthenmin_sym_diff_lowpreabelseiflt_msbkbkathenmin_sym_diff_lowprebaelseifka<kbthenmin_sym_diff_ltpreabelsemin_sym_diff_ltpreba(* [a] lies in the lower half of [b]: all the upper half of [b] differs. *)andmin_sym_diff_lowpreab=matchbwith|Empty->assertfalse|Nodenb->letx=min_sym_diffpreanb.rinifx>=0thenxelseifnb.l!=Emptythenmin_in(prelormbitnb.kk)nb.lelselowest(prelorkeynb.kk)nb.v(* Same most significant bit [m], [ka < kb]. In the upper halves, [a] holds
[a.l] and the key [ka - m], [b] holds [b.l] and the key [kb - m], which is
above everything in [a]. *)andmin_sym_diff_ltpreab=matcha,bwith|Nodena,Nodenb->letx=min_sym_diffprena.rnb.rinifx>=0thenxelseletm=mbitna.kkinletpre'=prelorminletka=prelorkeyna.kkin(* absolute key of the root of [a] *)letx=min_sym_diffpre'na.lnb.linifx>=0&&key_ofx<kathenxelseifx<0||key_ofx>kathen(* [b.l] does not have the key [ka]. *)lowestkana.velse(* [b.l] has the key [ka] and [a.l] does not. *)letd=na.vlxorlookup(keyna.kklxorm)nb.linifd<>0thenlowestkadelse(* The next element of [b] above [ka] differs. *)letx=min_gtpre'(keyna.kklxorm)nb.linifx>=0thenxelselowest(prelorkeynb.kk)nb.v|_->assertfalseletextract_shared_prefixs1s2=letx=min_sym_diff0s1s2inifx<0thens1,(empty,empty)elsebelowxs1,(at_leastxs1,at_leastxs2)(* -------------------------------------------------------------------------- *)(* Invariant checking. *)letcheckt=letfailfmt=Printf.ksprintffailwith("PatSet.check: "^^fmt)in(* [bound] is an exclusive upper bound on the keys, [-1] if unbounded. *)letrecchecktbound=matchtwith|Empty->()|Noden->letk=keyn.kkinifn.v=0thenfail"a node with an empty bitmap";ifn.kk<>enckthenfail"bad cached msb for key %d"k;ifbound>=0&&k>=boundthenfail"key %d is out of its bound %d"kbound;letm=mbitn.kkincheckn.l(k-m);checkn.rmincheckt(-1)