Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source
Source file dynarray.ml
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206(**************************************************************************)(* *)(* OCaml *)(* *)(* Gabriel Scherer, projet Partout, INRIA Paris-Saclay *)(* *)(* Copyright 2022 Institut National de Recherche en Informatique et *)(* en Automatique. *)(* *)(* All rights reserved. This file is distributed under the terms of *)(* the GNU Lesser General Public License version 2.1, with the *)(* special exception on linking described in the file LICENSE. *)(* *)(**************************************************************************)(* {2 The type ['a t]}
A dynamic array is represented using a backing array [arr] and
a [length]. It behaves as an array of size [length] -- the indices
from [0] to [length - 1] included contain user-provided values and
can be [get] and [set] -- but the length may also change in the
future by adding or removing elements at the end.
We use the following concepts;
- capacity: the length of the backing array:
[Array.length arr]
- live space: the portion of the backing array with
indices from [0] to [length - 1] included.
- empty space: the portion of the backing array
from [length] to the end of the backing array.
{2 Dummies}
We should not keep a user-provided value in the empty space, as
this could extend its lifetime and may result in memory leaks of
arbitrary size. Functions that remove elements from the dynamic
array, such as [pop_last] or [truncate], must really erase the
element from the backing array.
To do so, we use an unsafe/magical [dummy] in the empty array. This
dummy is *not* type-safe, it is not a valid value of type ['a], so
we must be very careful never to return it to the user. After
accessing any element of the array, we must check that it is not
the dummy. In particular, this dummy must be distinct from any
other value the user could provide -- we ensure this by using
a dynamically-allocated mutable reference as our dummy.
{2 Invariants and valid states}
We enforce the invariant that [length >= 0] at all times.
we rely on this invariant for optimization.
The following conditions define what we call a "valid" dynarray:
- valid length: [length <= Array.length arr]
- no missing element in the live space:
forall i, [0 <= i < length] implies [arr.(i) != dummy]
- no element in the empty space:
forall i, [length <= i < Array.length arr] implies [arr.(i) == dummy]
Unfortunately, we cannot easily enforce validity as an invariant in
presence of concurrent updates. We can thus observe dynarrays in
"invalid states". Our implementation may raise exceptions or return
incorrect results on observing invalid states, but of course it
must preserve memory safety.
{3 Dummies and flat float arrays}
OCaml performs a dynamic optimization of the representation of
float arrays, which is incompatible with our use of a dummy
value: if we initialize an array with user-provided elements,
it may get an optimized into a "flat float array", and
writing our non-float dummy into it would crash.
To avoid interactions between unsafe dummies and flat float arrays,
we ensure that the arrays that we use are never initialized with
floating point values. In that case we will always get a non-flat
array, and storing float values inside those is safe
(if less efficient). We call this the 'no-flat-float' invariant.
{3 Marshalling dummies}
There is a risk of interaction between dummies and
marshalling. If we use a global dynamically-allocated dummy
for the whole module, we are not robust to a user marshalling
a dynarray and unmarshalling it inside another program with
a different global dummy.
The trick is to store the dummy that we use in the dynarray
metadata record. Marshalling the dynarray will then preserve the
physical equality between this dummy field and dummy elements in
the array, as expected.
This reasoning assumes that marshalling does not use the
[No_sharing] flag. To ensure that users do not marshal dummies
with [No_sharing], we use a recursive/cyclic dummy that would make
such marshalling loop forever. (This is not nice, but better than
segfaulting later for obscure reasons.)
*)(** The [Dummy] module encapsulates the low-level magic we use
for dummies, providing a strongly-typed API that:
- makes it explicit where dummies are used
- makes it hard to mistakenly mix data using distinct dummies,
which would be unsound *)moduleDummy:sig(** {4 Dummies} *)type'stampdummy(** The type of dummies is parametrized by a ['stamp] variable,
so that two dummies with different stamps cannot be confused
together. *)typefresh_dummy=Fresh:'stampdummy->fresh_dummyvalfresh:unit->fresh_dummy(** The type of [fresh] enforces a fresh/unknown/opaque stamp for
the returned dummy, distinct from all previous stamps. *)(** {4 Values or dummies} *)type('a,'stamp)with_dummy(** a value of type [('a, 'stamp) with_dummy] is either a proper
value of type ['a] or a dummy with stamp ['stamp]. *)valof_val:'a->('a,'stamp)with_dummyvalof_dummy:'stampdummy->('a,'stamp)with_dummyvalis_dummy:('a,'stamp)with_dummy->'stampdummy->boolvalunsafe_get:('a,'stamp)with_dummy->'a(** [unsafe_get v] can only be called safely if [is_dummy v dummy]
is [false].
We could instead provide
[val find : ('a, 'stamp) with_dummy -> ('a, 'stamp dummy) result]
but this would involve intermediary allocations.
{[match find x with
| None -> ...
| Some v -> ...]}
can instead be written
{[if Dummy.is_dummy x
then ...
else let v = Dummy.unsafe_get x in ...]}
*)(** {4 Arrays of values or dummies} *)moduleArray:sigvalmake:int->'a->dummy:'stampdummy->('a,'stamp)with_dummyarrayvalinit:int->(int->'a)->dummy:'stampdummy->('a,'stamp)with_dummyarrayvalcopy:'aarray->dummy:'stampdummy->('a,'stamp)with_dummyarrayvalunsafe_nocopy:'aarray->dummy:'stampdummy->('a,'stamp)with_dummyarray(** [unsafe_nocopy] assumes that the input array was created
locally and will not be used anymore (in the spirit of
[Bytes.unsafe_to_string]), and avoids a copy of the input
array when possible. *)valblit_array:'aarray->int->('a,'stamp)with_dummyarray->int->len:int->unitvalblit:('a,'stamp1)with_dummyarray->'stamp1dummy->int->('a,'stamp2)with_dummyarray->'stamp2dummy->int->len:int->unitvalprefix:('a,'stamp)with_dummyarray->int->('a,'stamp)with_dummyarrayvalextend:('a,'stamp)with_dummyarray->length:int->dummy:'stampdummy->new_capacity:int->('a,'stamp)with_dummyarrayendend=struct(* We want to use a cyclic value so that No_sharing marshalling
fails loudly, but we want also comparison of dynarrays to work
as expected, and not loop forever.
Our approach is to use an object value that contains a cycle.
Objects are compared by their unique id, so comparison is not
structural and will not loop on the cycle, but marshalled
by content, so marshalling without sharing will fail on the cycle.
(It is a bit tricky to build an object that does not contain
functional values where marshalling fails, see [fresh ()] below
for how we do it.) *)type'stampdummy=<>typefresh_dummy=Fresh:'stampdummy->fresh_dummyletfresh()=(* dummies and marshalling: we intentionally
use a cyclic value here. *)letr=refNoneinignore(* hack: this primitive is required by the object expression below,
ensure that 'make depend' notices it. *)CamlinternalOO.create_object_opt;letdummy=objectvalx=rendinr:=Somedummy;Freshdummytype('a,'stamp)with_dummy='aletof_valv=vletof_dummy(typeastamp)(dummy:stampdummy)=(Obj.magicdummy:(a,stamp)with_dummy)letis_dummyvdummy=v==of_dummydummyletunsafe_getv=vmoduleArray=structletmakenx~dummy=ifObj.(tag(reprx)<>double_tag)thenArray.maken(of_valx)elsebeginletarr=Array.maken(of_dummydummy)inArray.fillarr0n(of_valx);arrendletcopya~dummy=ifObj.(tag(repra)<>double_array_tag)thenArray.copyaelsebeginletn=Array.lengthainletarr=Array.maken(of_dummydummy)infori=0ton-1doArray.unsafe_setarri(of_val(Array.unsafe_getai));done;arrendletunsafe_nocopya~dummy=ifObj.(tag(repra)<>double_array_tag)thenaelsecopya~dummyletinitnf~dummy=letarr=Array.maken(of_dummydummy)infori=0ton-1doArray.unsafe_setarri(of_val(fi))done;arrletblit_arraysrcsrc_posdstdst_pos~len=ifObj.(tag(reprsrc)<>double_array_tag)thenArray.blitsrcsrc_posdstdst_poslenelsebeginfori=0tolen-1dodst.(dst_pos+i)<-of_valsrc.(src_pos+i)done;endletblitsrcsrc_dummysrc_posdstdst_dummydst_pos~len=ifsrc_dummy==dst_dummythenArray.blitsrcsrc_posdstdst_poslenelsebeginiflen<0||src_pos<0||src_pos+len<0(* overflow check *)||src_pos+len>Array.lengthsrc||dst_pos<0||dst_pos+len<0(* overflow check *)||dst_pos+len>Array.lengthdstthenbegin(* We assume that the caller has already checked this and
will raise a proper error. The check here is only for
memory safety, it should not be reached and it is okay if
the error is uninformative. *)assertfalse;end;(* We failed the check [src_dummy == dst_dummy] above, so we
know that in fact [src != dst] -- two dynarrays with
distinct dummies cannot share the same backing arrays. *)assert(src!=dst);(* In particular, the source and destination arrays cannot
overlap, so we can always copy in ascending order without
risking overwriting an element needed later. *)fori=0tolen-1doArray.unsafe_setdst(dst_pos+i)(Array.unsafe_getsrc(src_pos+i));doneendletprefixarrn=(* Note: the safety of the [Array.sub] call below, with respect to
our 'no-flat-float' invariant, relies on the fact that
[Array.sub] checks the tag of the input array, not whether the
elements themselves are float.
To avoid relying on this undocumented property we could use
[Array.make length dummy] and then set values in a loop, but this
would result in [caml_modify] rather than [caml_initialize]. *)Array.subarr0nletextendarr~length~dummy~new_capacity=(* 'no-flat-float' invariant: we initialise the array with our
non-float dummy to get a non-flat array. *)letnew_arr=Array.makenew_capacity(of_dummydummy)inArray.blitarr0new_arr0length;new_arrendendtype'at=Pack:('a,'stamp)t_->'at[@@unboxed]and('a,'stamp)t_={mutablelength:int;mutablearr:('a,'stamp)Dummy.with_dummyarray;dummy:'stampDummy.dummy;}letglobal_dummy=Dummy.fresh()(* We need to ensure that dummies are never exposed to the user as
values of type ['a]. Including the dummy in the dynarray metadata
is necessary for marshalling to behave correctly, but there is no
obligation to create a fresh dummy for each new dynarray, we can
use a global dummy.
On the other hand, unmarshalling may precisely return a dynarray
with another dummy: we cannot assume that all dynarrays use this
global dummy. The existential hiding of the dummy ['stamp]
parameter helps us to avoid this assumption. *)moduleError=structlet[@inlinenever]index_out_of_boundsf~i~length=iflength=0thenPrintf.ksprintfinvalid_arg"Dynarray.%s: index %d out of bounds (empty dynarray)"fielsePrintf.ksprintfinvalid_arg"Dynarray.%s: index %d out of bounds (0..%d)"fi(length-1)let[@inlinenever]negative_length_requestedfn=Printf.ksprintfinvalid_arg"Dynarray.%s: negative length %d requested"fnlet[@inlinenever]negative_capacity_requestedfn=Printf.ksprintfinvalid_arg"Dynarray.%s: negative capacity %d requested"fnlet[@inlinenever]requested_length_out_of_boundsfrequested_length=Printf.ksprintfinvalid_arg"Dynarray.%s: cannot grow to requested length %d (max_array_length is %d)"frequested_lengthSys.max_array_length(* When observing an invalid state ([missing_element],
[invalid_length]), we do not give the name of the calling function
in the error message, as the error is related to invalid operations
performed earlier, and not to the callsite of the function
itself. *)letinvalid_state_description="Invalid dynarray (unsynchronized concurrent length change)"let[@inlinenever]missing_element~i~length=Printf.ksprintfinvalid_arg"%s: missing element at position %d < length %d"invalid_state_descriptionilengthlet[@inlinenever]invalid_length~length~capacity=Printf.ksprintfinvalid_arg"%s: length %d > capacity %d"invalid_state_descriptionlengthcapacitylet[@inlinenever]length_change_during_iterationf~expected~observed=Printf.ksprintfinvalid_arg"Dynarray.%s: a length change from %d to %d occurred during iteration"fexpectedobserved(* When an [Empty] element is observed unexpectedly at index [i],
it may be either an out-of-bounds access or an invalid-state situation
depending on whether [i <= length]. *)let[@inlinenever]unexpected_empty_elementf~i~length=ifi<lengththenmissing_element~i~lengthelseindex_out_of_boundsf~i~lengthlet[@inlinenever]empty_dynarrayf=Printf.ksprintfinvalid_arg"Dynarray.%s: empty array"fend(* Detecting iterator invalidation.
See {!iter} below for a detailed usage example.
*)letcheck_same_lengthf(Packa)~length=letlength_a=a.lengthiniflength<>length_athenError.length_change_during_iterationf~expected:length~observed:length_a(** Careful unsafe access. *)(* Postcondition on non-exceptional return:
[length <= Array.length arr] *)let[@inlinealways]check_valid_lengthlengtharr=letcapacity=Array.lengtharriniflength>capacitythenError.invalid_length~length~capacity(* Precondition: [0 <= i < length <= Array.length arr]
This precondition is typically guaranteed by knowing
[0 <= i < length] and calling [check_valid_length length arr].*)let[@inlinealways]unsafe_getarr~dummy~i~length=letv=Array.unsafe_getarriinifDummy.is_dummyvdummythenError.missing_element~i~lengthelseDummy.unsafe_getv(** {1:dynarrays Dynamic arrays} *)letcreate()=letDummy.Freshdummy=global_dummyinPack{length=0;arr=[||];dummy=dummy;}letmakenx=ifn<0thenError.negative_length_requested"make"n;letDummy.Freshdummy=global_dummyinletarr=Dummy.Array.makenx~dummyinPack{length=n;arr;dummy;}letinit(typea)n(f:int->a):at=ifn<0thenError.negative_length_requested"init"n;letDummy.Freshdummy=global_dummyinletarr=Dummy.Array.init~dummynfinPack{length=n;arr;dummy;}letget(typea)(Packa:at)i=(* This implementation will propagate an [Invalid_argument] exception
from array lookup if the index is out of the backing array,
instead of using our own [Error.index_out_of_bounds]. This is
allowed by our specification, and more efficient -- no need to
check that [length a <= capacity a] in the fast path. *)letv=a.arr.(i)inifDummy.is_dummyva.dummythenError.unexpected_empty_element"get"~i~length:a.lengthelseDummy.unsafe_getvletset(Packa)ix=let{arr;length;_}=ainifi>=lengththenError.index_out_of_bounds"set"~i~lengthelsearr.(i)<-Dummy.of_valxletlength(Packa)=a.lengthletis_empty(Packa)=(a.length=0)letcopy(typea)(Pack{length;arr;dummy}:at):at=check_valid_lengthlengtharr;(* use [length] as the new capacity to make
this an O(length) operation. *)letarr=Dummy.Array.prefixarrlengthinPack{length;arr;dummy}letget_last(Packa)=let{arr;length;dummy}=aincheck_valid_lengthlengtharr;(* We know [length <= capacity a]. *)iflength=0thenError.empty_dynarray"get_last";(* We know [length > 0]. *)unsafe_getarr~dummy~i:(length-1)~lengthletfind_last(Packa)=let{arr;length;dummy}=aincheck_valid_lengthlengtharr;(* We know [length <= capacity a]. *)iflength=0thenNoneelse(* We know [length > 0]. *)Some(unsafe_getarr~dummy~i:(length-1)~length)(** {1:removing Removing elements} *)letpop_last(Packa)=let{arr;length;dummy}=aincheck_valid_lengthlengtharr;(* We know [length <= capacity a]. *)iflength=0thenraiseNot_found;letlast=length-1in(* We know [length > 0] so [last >= 0]. *)letv=unsafe_getarr~dummy~i:last~lengthinArray.unsafe_setarrlast(Dummy.of_dummydummy);a.length<-last;vletpop_last_opta=matchpop_lastawith|exceptionNot_found->None|x->Somexletremove_last(Packa)=letlast=a.length-1iniflast>=0thenbegina.length<-last;a.arr.(last)<-Dummy.of_dummya.dummy;endlettruncate(Packa)n=ifn<0thenError.negative_length_requested"truncate"n;let{arr;length;dummy}=ainiflength<=nthen()elsebegina.length<-n;Array.fillarrn(length-n)(Dummy.of_dummydummy)endletcleara=truncatea0(** {1:capacity Backing array and capacity} *)letcapacity(Packa)=Array.lengtha.arrletnext_capacityn=letn'=(* For large values of n, we use 1.5 as our growth factor.
For smaller values of n, we grow more aggressively to avoid
reallocating too much when accumulating elements into an empty
array.
The constants "512 words" and "8 words" below are taken from
https://github.com/facebook/folly/blob/
c06c0f41d91daf1a6a5f3fc1cd465302ac260459/folly/FBVector.h#L1128-L1157
*)ifn<=512thenn*2elsen+n/2in(* jump directly from 0 to 8 *)min(max8n')Sys.max_array_lengthletensure_capacity(Packa)capacity_request=letarr=a.arrinletcur_capacity=Array.lengtharrinifcapacity_request<0thenError.negative_capacity_requested"ensure_capacity"capacity_requestelseifcur_capacity>=capacity_requestthen(* This is the fast path, the code up to here must do as little as
possible. (This is why we don't use [let {arr; length} = a] as
usual, the length is not needed in the fast path.)*)()elsebeginifcapacity_request>Sys.max_array_lengththenError.requested_length_out_of_bounds"ensure_capacity"capacity_request;letnew_capacity=(* We use either the next exponential-growth strategy,
or the requested strategy, whichever is bigger.
Compared to only using the exponential-growth strategy, this
lets us use less memory by avoiding any overshoot whenever
the capacity request is noticeably larger than the current
capacity.
Compared to only using the requested capacity, this avoids
losing the amortized guarantee: we allocated "exponentially
or more", so the amortization holds. In particular, notice
that repeated calls to [ensure_capacity a (length a + 1)]
will have amortized-linear rather than quadratic complexity.
*)max(next_capacitycur_capacity)capacity_requestinassert(new_capacity>0);letnew_arr=Dummy.Array.extendarr~length:a.length~dummy:a.dummy~new_capacityina.arr<-new_arr;(* postcondition: *)assert(0<=capacity_request);assert(capacity_request<=Array.lengthnew_arr);endletensure_extra_capacityaextra_capacity_request=ensure_capacitya(lengtha+extra_capacity_request)letfit_capacity(Packa)=ifArray.lengtha.arr=a.lengththen()elsea.arr<-Dummy.Array.prefixa.arra.lengthletset_capacity(Packa)n=ifn<0thenError.negative_capacity_requested"set_capacity"n;letarr=a.arrinletcur_capacity=Array.lengtharrinifn<cur_capacitythenbegina.length<-mina.lengthn;a.arr<-Dummy.Array.prefixarrn;endelseifn>cur_capacitythenbegina.arr<-Dummy.Array.extendarr~length:a.length~dummy:a.dummy~new_capacity:n;endletreset(Packa)=a.length<-0;a.arr<-[||](** {1:adding Adding elements} *)(* We chose an implementation of [add_last a x] that behaves correctly
in presence of asynchronous / re-entrant code execution around
allocations and poll points: if another thread or a callback gets
executed on allocation, we add the element at the new end of the
dynamic array.
(We do not give the same guarantees in presence of concurrent
parallel updates, which are much more expensive to protect
against.)
*)(* [add_last_if_room a v] only writes the value if there is room, and
returns [false] otherwise. *)let[@inline]add_last_if_room(Packa)v=let{arr;length;_}=ain(* we know [0 <= length] *)iflength>=Array.lengtharrthenfalseelsebegin(* we know [0 <= length < Array.length arr] *)a.length<-length+1;Array.unsafe_setarrlength(Dummy.of_valv);trueendletadd_lastax=ifadd_last_if_roomaxthen()elsebegin(* slow path *)letrecgrow_and_addax=ensure_extra_capacitya1;ifnot(add_last_if_roomax)thengrow_and_addaxingrow_and_addaxendletrecappend_listali=matchliwith|[]->()|x::xs->add_lastax;append_listaxsletappend_iteraiterb=iter(funx->add_lastax)bletappend_seqaseq=Seq.iter(funx->add_lastax)seq(* blitting *)letblit_assume_room(Packsrc)src_possrc_length(Packdst)dst_posdst_lengthblit_length=(* The caller of [blit_assume_room] typically calls
[ensure_capacity] right before. This could run asynchronous
code. We want to fail reliably on any asynchronous length change,
as it may invalidate the source and target ranges provided by the
user. So we double-check that the lengths have not changed. *)letsrc_arr=src.arrinletdst_arr=dst.arrincheck_same_length"blit"(Packsrc)~length:src_length;check_same_length"blit"(Packdst)~length:dst_length;ifdst_pos+blit_length>dst_lengththenbegindst.length<-dst_pos+blit_length;end;(* note: [src] and [dst] may be equal when self-blitting, so
[src.length] may have been mutated here. *)Dummy.Array.blitsrc_arrsrc.dummysrc_posdst_arrdst.dummydst_pos~len:blit_lengthletblit~src~src_pos~dst~dst_pos~len=letsrc_length=lengthsrcinletdst_length=lengthdstiniflen<0thenPrintf.ksprintfinvalid_arg"Dynarray.blit: invalid blit length (%d)"len;ifsrc_pos<0||src_pos+len>src_lengththenPrintf.ksprintfinvalid_arg"Dynarray.blit: invalid source region (%d..%d) \
in source dynarray of length %d"src_pos(src_pos+len)src_length;ifdst_pos<0||dst_pos>dst_lengththenPrintf.ksprintfinvalid_arg"Dynarray.blit: invalid target region (%d..%d) \
in target dynarray of length %d"dst_pos(dst_pos+len)dst_length;ensure_capacitydst(dst_pos+len);blit_assume_roomsrcsrc_possrc_lengthdstdst_posdst_lengthlen(* append_array: same [..._if_room] and loop logic as [add_last]. *)letappend_array_if_room(Packa)b=let{arr;length=length_a;_}=ainletlength_b=Array.lengthbiniflength_a+length_b>Array.lengtharrthenfalseelsebegin(* Note: we intentionally update the length *before* filling the
elements. This "reserve before fill" approach provides better
behavior than "fill then notify" in presence of reentrant
modifications (which may occur on [blit] below):
- If some code asynchronously adds new elements after this
length update, they will go after the space we just reserved,
and in particular no addition will be lost. If instead we
updated the length after the loop, any asynchronous addition
during the loop could be erased or erase one of our additions,
silently, without warning the user.
- If some code asynchronously iterates on the dynarray, or
removes elements, or otherwise tries to access the
reserved-but-not-yet-filled space, it will get a clean "missing
element" error. This is worse than with the fill-then-notify
approach where the new elements would only become visible
(to iterators, for removal, etc.) altogether at the end of
loop.
To summarise, "reserve before fill" is better on add-add races,
and "fill then notify" is better on add-remove or add-iterate
races. But the key difference is the failure mode:
reserve-before fails on add-remove or add-iterate races with
a clean error, while notify-after fails on add-add races with
silently disappearing data. *)a.length<-length_a+length_b;Dummy.Array.blit_arrayb0arrlength_a~len:length_b;trueendletappend_arrayab=ifappend_array_if_roomabthen()elsebegin(* slow path *)letrecgrow_and_appendab=ensure_extra_capacitya(Array.lengthb);ifnot(append_array_if_roomab)thengrow_and_appendabingrow_and_appendabend(* append: same [..._if_room] and loop logic as [add_last]. *)(* It is a programming error to mutate the length of [b] during a call
to [append a b]. To detect this mistake we keep track of the length
of [b] throughout the computation and check it that does not
change.
*)letappend_if_room(Packa)b~length_b=let{arr=arr_a;length=length_a;_}=ainiflength_a+length_b>Array.lengtharr_athenfalseelsebegin(* blit [0..length_b-1]
into [length_a..length_a+length_b-1]. *)blit_assume_roomb0length_b(Packa)length_alength_alength_b;check_same_length"append"b~length:length_b;trueendletappendab=letlength_b=lengthbinifappend_if_roomab~length_bthen()elsebegin(* slow path *)letrecgrow_and_appendab~length_b=ensure_extra_capacityalength_b;(* Eliding the [check_same_length] call below would be wrong in
the case where [a] and [b] are aliases of each other, we
would get into an infinite loop instead of failing.
We could push the call to [append_if_room] itself, but we
prefer to keep it in the slow path. *)check_same_length"append"b~length:length_b;ifnot(append_if_roomab~length_b)thengrow_and_appendab~length_bingrow_and_appendab~length_bend(** {1:iteration Iteration} *)(* The implementation choice that we made for iterators is the one
that maximizes efficiency by avoiding repeated bound checking: we
check the length of the dynamic array once at the beginning, and
then only operate on that portion of the dynarray, ignoring
elements added in the meantime.
The specification states that it is a programming error to mutate
the length of the array during iteration. We check for this and
raise an error on size change.
Note that we may still miss some transient state changes that cancel
each other and leave the length unchanged at the next check.
*)letiter_fka=letPack{arr;length;dummy}=ain(* [check_valid_length length arr] is used for memory safety, it
guarantees that the backing array has capacity at least [length],
allowing unsafe array access.
[check_same_length] is used for correctness, it lets the function
fail more often if we discover the programming error of mutating
the length during iteration.
We could, naively, call [check_same_length] at each iteration of
the loop (before or after, or both). However, notice that this is
not necessary to detect the removal of elements from [a]: if
elements have been removed by the time the [for] loop reaches
them, then [unsafe_get] will itself fail with an [Invalid_argument]
exception. We only need to detect the addition of new elements to
[a] during iteration, and for this it is enough to call
[check_same_length] once at the end.
Calling [check_same_length] more often could catch more
programming errors, but the only errors that we miss with this
optimization are those that keep the array size constant --
additions and deletions that cancel each other. We consider this
an acceptable tradeoff.
*)check_valid_lengthlengtharr;fori=0tolength-1dok(unsafe_getarr~dummy~i~length);done;check_same_lengthfa~lengthletiterka=iter_"iter"kaletiterika=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;fori=0tolength-1doki(unsafe_getarr~i~dummy~length);done;check_same_length"iteri"a~lengthletmapfa=letPack{arr=arr_in;length;dummy}=aincheck_valid_lengthlengtharr_in;letarr_out=Array.makelength(Dummy.of_dummydummy)infori=0tolength-1doArray.unsafe_setarr_outi(Dummy.of_val(f(unsafe_getarr_in~dummy~i~length)))done;letres=Pack{length;arr=arr_out;dummy;}incheck_same_length"map"a~length;resletmapifa=letPack{arr=arr_in;length;dummy}=aincheck_valid_lengthlengtharr_in;letarr_out=Array.makelength(Dummy.of_dummydummy)infori=0tolength-1doArray.unsafe_setarr_outi(Dummy.of_val(fi(unsafe_getarr_in~dummy~i~length)))done;letres=Pack{length;arr=arr_out;dummy;}incheck_same_length"mapi"a~length;resletfold_leftfacca=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letr=refaccinfori=0tolength-1doletv=unsafe_getarr~dummy~i~lengthinr:=f!rv;done;check_same_length"fold_left"a~length;!rletfold_rightfaacc=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letr=refaccinfori=length-1downto0doletv=unsafe_getarr~dummy~i~lengthinr:=fv!r;done;check_same_length"fold_right"a~length;!rletexistspa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopparrdummyilength=ifi=lengththenfalseelsep(unsafe_getarr~dummy~i~length)||loopparrdummy(i+1)lengthinletres=loopparrdummy0lengthincheck_same_length"exists"a~length;resletfor_allpa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopparrdummyilength=ifi=lengththentrueelsep(unsafe_getarr~dummy~i~length)&&loopparrdummy(i+1)lengthinletres=loopparrdummy0lengthincheck_same_length"for_all"a~length;resletfilterfa=letb=create()initer_"filter"(funx->iffxthenadd_lastbx)a;bletfilter_mapfa=letb=create()initer_"filter_map"(funx->matchfxwith|None->()|Somey->add_lastby)a;bletmemxa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopi=ifi=lengththenfalseelseifStdlib.compare(unsafe_getarr~dummy~i~length)x=0thentrueelseloop(succi)inletres=loop0incheck_same_length"mem"a~length;resletmemqxa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopi=ifi=lengththenfalseelseif(unsafe_getarr~dummy~i~length)==xthentrueelseloop(succi)inletres=loop0incheck_same_length"memq"a~length;resletfind_optpa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopi=ifi=lengththenNoneelseletx=unsafe_getarr~dummy~i~lengthinifpxthenSomexelseloop(succi)inletres=loop0incheck_same_length"find_opt"a~length;resletfind_indexpa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopi=ifi=lengththenNoneelseletx=unsafe_getarr~dummy~i~lengthinifpxthenSomeielseloop(succi)inletres=loop0incheck_same_length"find_index"a~length;resletfind_mappa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopi=ifi=lengththenNoneelsematchp(unsafe_getarr~dummy~i~length)with|None->loop(succi)|Some_asr->rinletres=loop0incheck_same_length"find_map"a~length;resletfind_mapipa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecloopi=ifi=lengththenNoneelsematchpi(unsafe_getarr~dummy~i~length)with|None->loop(succi)|Some_asr->rinletres=loop0incheck_same_length"find_mapi"a~length;resletequaleqa1a2=letPack{arr=arr1;length=length;dummy=dum1}=a1inletPack{arr=arr2;length=len2;dummy=dum2}=a2iniflength<>len2thenfalseelsebegincheck_valid_lengthlengtharr1;check_valid_lengthlengtharr2;letrecloopi=ifi=lengththentrueelseeq(unsafe_getarr1~dummy:dum1~i~length)(unsafe_getarr2~dummy:dum2~i~length)&&loop(i+1)inletr=loop0incheck_same_length"equal"a1~length;check_same_length"equal"a2~length;rendletcomparecmpa1a2=letPack{arr=arr1;length=length;dummy=dum1}=a1inletPack{arr=arr2;length=len2;dummy=dum2}=a2iniflength<>len2thenlength-len2elsebegincheck_valid_lengthlengtharr1;check_valid_lengthlengtharr2;letrecloopi=ifi=lengththen0elseletc=cmp(unsafe_getarr1~dummy:dum1~i~length)(unsafe_getarr2~dummy:dum2~i~length)inifc<>0thencelseloop(i+1)inletr=loop0incheck_same_length"compare"a1~length;check_same_length"compare"a2~length;rend(** {1:conversions Conversions to other data structures} *)(* The eager [to_*] conversion functions behave similarly to iterators
in presence of updates during computation. The [*_reentrant]
functions obey their more permissive specification, which tolerates
any concurrent update. *)letof_arraya=letlength=Array.lengthainletDummy.Freshdummy=global_dummyinletarr=Dummy.Array.copya~dummyinPack{length;arr;dummy;}letto_arraya=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letres=Array.initlength(funi->unsafe_getarr~dummy~i~length)incheck_same_length"to_array"a~length;resletof_listli=leta=Array.of_listliinletlength=Array.lengthainletDummy.Freshdummy=global_dummyinletarr=Dummy.Array.unsafe_nocopya~dummyinPack{length;arr;dummy;}letto_lista=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letl=ref[]infori=length-1downto0dol:=unsafe_getarr~dummy~i~length::!ldone;check_same_length"to_list"a~length;!lletof_seqseq=letinit=create()inappend_seqinitseq;initletto_seqa=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecauxi=fun()->check_same_length"to_seq"a~length;ifi>=lengththenSeq.Nilelsebeginletv=unsafe_getarr~dummy~i~lengthinSeq.Cons(v,aux(i+1))endinaux0letto_seq_reentranta=letrecauxi=fun()->ifi>=lengthathenSeq.Nilelsebeginletv=getaiinSeq.Cons(v,aux(i+1))endinaux0letto_seq_reva=letPack{arr;length;dummy}=aincheck_valid_lengthlengtharr;letrecauxi=fun()->check_same_length"to_seq_rev"a~length;ifi<0thenSeq.Nilelsebeginletv=unsafe_getarr~dummy~i~lengthinSeq.Cons(v,aux(i-1))endinaux(length-1)letto_seq_rev_reentranta=letrecauxi=fun()->ifi<0thenSeq.Nilelseifi>=lengthathen(* If some elements have been removed in the meantime, we skip
those elements and continue with the new end of the array. *)aux(lengtha-1)()elsebeginletv=getaiinSeq.Cons(v,aux(i-1))endinaux(lengtha-1)