123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492(*----------------------------------------------------------------------------
Copyright (c) 2016 Inhabited Type LLC.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------*)typebigstring=Bigstringaf.ttype'aiovec={buffer:'a;off:int;len:int}exceptionDequeue_emptymoduleDeque(T:sigtypetvalsentinel:tend):sigtypeelem=T.ttypetvalcreate:int->tvalis_empty:t->boolvalenqueue:elem->t->unitvaldequeue_exn:t->elemvalenqueue_front:elem->t->unitvalmap_to_list:t->f:(elem->'b)->'blistend=structtypeelem=T.ttypet={mutableelements:elemarray;mutablefront:int;mutableback:int}letsentinel=T.sentinelletcreatesize={elements=Array.makesizesentinel;front=0;back=0}letis_emptyt=t.front=t.backletensure_spacet=ift.back=Array.lengtht.elements-1thenbeginletlen=t.back-t.frontinift.front>0thenbegin(* Shift everything to the front of the array and then clear out
* dangling pointers to elements from their previous locations. *)Array.blitt.elementst.frontt.elements0len;Array.fillt.elementslent.frontsentinelendelsebeginletold=t.elementsinletnew_=Array.(make(2*lengthold)sentinel)inArray.blitoldt.frontnew_0len;t.elements<-new_end;t.front<-0;t.back<-lenendletenqueueet=ensure_spacet;t.elements.(t.back)<-e;t.back<-t.back+1letdequeue_exnt=ifis_emptytthenraise_notraceDequeue_emptyelseletresult=Array.unsafe_gett.elementst.frontinArray.unsafe_sett.elementst.frontsentinel;t.front<-t.front+1;resultletenqueue_frontet=(* This is in general not true for Deque data structures, but the usage
* below ensures that there is always space to push an element back on the
* front. An [enqueue_front] is always preceded by a [dequeue], with no
* intervening operations. *)assert(t.front>0);t.front<-t.front-1;t.elements.(t.front)<-eletmap_to_listt~f=letresult=ref[]infori=t.back-1downtot.frontdoresult:=ft.elements.(i)::!resultdone;!resultendmoduleIOVec=structletcreatebuffer~off~len={buffer;off;len}letlengtht=t.lenletshift{buffer;off;len}n=assert(n<len);{buffer;off=off+n;len=len-n}letlengthvts=letreclooptsacc=matchtswith|[]->acc|iovec::ts->loopts(lengthiovec+acc)inloopts0endmoduleFlushed_reason=structtypet=Shift|Drain|Nothing_pendingendmoduleBuffers=Deque(structtypet=bigstringiovecletsentinel=letdeadbeef="\222\173\190\239"inletlen=String.lengthdeadbeefinletbuffer=Bigstringaf.createleninString.iteri(Bigstringaf.unsafe_setbuffer)deadbeef;{buffer;off=0;len}end)moduleFlushes=Deque(structtypet=int*(Flushed_reason.t->unit)letsentinel=0,fun_->()end)typet={mutablebuffer:bigstring;mutablescheduled_pos:int;mutablewrite_pos:int;scheduled:Buffers.t;flushed:Flushes.t;mutablebytes_received:int;mutablebytes_written:int;mutableclosed:bool;mutableyield:bool}typeoperation=[|`Writevofbigstringioveclist|`Yield|`Close]letof_bigstringbuffer={buffer;write_pos=0;scheduled_pos=0;scheduled=Buffers.create4;flushed=Flushes.create1;bytes_received=0;bytes_written=0;closed=false;yield=false}letcreatesize=of_bigstring(Bigstringaf.createsize)letwritable_exnt=ift.closedthenfailwith"cannot write to closed writer"letschedule_iovect?(off=0)~lenbuffer=t.bytes_received<-t.bytes_received+len;Buffers.enqueue(IOVec.createbuffer~off~len)t.scheduledletflush_buffert=letlen=t.write_pos-t.scheduled_posiniflen>0thenbeginletoff=t.scheduled_posinschedule_iovect~off~lent.buffer;t.scheduled_pos<-t.write_posendletflush_with_reasontf=t.yield<-false;flush_buffert;ifBuffers.is_emptyt.scheduledthenfFlushed_reason.Nothing_pendingelseFlushes.enqueue(t.bytes_received,f)t.flushedletflushtf=flush_with_reasont(fun_->f())letfree_bytes_in_buffert=letbuf_len=Bigstringaf.lengtht.bufferinbuf_len-t.write_posletschedule_bigstringt?(off=0)?lena=writable_exnt;flush_buffert;letlen=matchlenwith|None->Bigstringaf.lengtha-off|Somelen->leniniflen>0thenschedule_iovect~off~lenaletensure_spacetlen=iffree_bytes_in_buffert<lenthenbeginflush_buffert;t.buffer<-Bigstringaf.create(max(Bigstringaf.lengtht.buffer)len);t.write_pos<-0;t.scheduled_pos<-0endletwrite_gent~length~blit?(off=0)?lena=writable_exnt;letlen=matchlenwith|None->lengtha-off|Somelen->leninensure_spacetlen;blita~src_off:offt.buffer~dst_off:t.write_pos~len;t.write_pos<-t.write_pos+lenletwrite_string=letlength=String.lengthinletblit=Bigstringaf.unsafe_blit_from_stringinfunt?off?lena->write_gent~length~blit?off?lenaletwrite_bytes=letlength=Bytes.lengthinletblit=Bigstringaf.unsafe_blit_from_bytesinfunt?off?lena->write_gent~length~blit?off?lenaletwrite_bigstring=letlength=Bigstringaf.lengthinletblit=Bigstringaf.unsafe_blitinfunt?off?lena->write_gent~length~blit?off?lenaletwrite_chartc=writable_exnt;ensure_spacet1;Bigstringaf.unsafe_sett.buffert.write_posc;t.write_pos<-t.write_pos+1letwrite_uint8tb=writable_exnt;ensure_spacet1;Bigstringaf.unsafe_sett.buffert.write_pos(Char.unsafe_chrb);t.write_pos<-t.write_pos+1moduleBE=structletwrite_uint16ti=writable_exnt;ensure_spacet2;Bigstringaf.unsafe_set_int16_bet.buffert.write_posi;t.write_pos<-t.write_pos+2letwrite_uint32ti=writable_exnt;ensure_spacet4;Bigstringaf.unsafe_set_int32_bet.buffert.write_posi;t.write_pos<-t.write_pos+4letwrite_uint48ti=writable_exnt;ensure_spacet6;Bigstringaf.unsafe_set_int32_bet.buffert.write_posInt64.(to_int32(shift_right_logicali4));Bigstringaf.unsafe_set_int16_bet.buffer(t.write_pos+2)Int64.(to_inti);t.write_pos<-t.write_pos+6letwrite_uint64ti=writable_exnt;ensure_spacet8;Bigstringaf.unsafe_set_int64_bet.buffert.write_posi;t.write_pos<-t.write_pos+8letwrite_floattf=writable_exnt;ensure_spacet4;Bigstringaf.unsafe_set_int32_bet.buffert.write_pos(Int32.bits_of_floatf);t.write_pos<-t.write_pos+4letwrite_doubletd=writable_exnt;ensure_spacet8;Bigstringaf.unsafe_set_int64_bet.buffert.write_pos(Int64.bits_of_floatd);t.write_pos<-t.write_pos+8endmoduleLE=structletwrite_uint16ti=writable_exnt;ensure_spacet2;Bigstringaf.unsafe_set_int16_let.buffert.write_posi;t.write_pos<-t.write_pos+2letwrite_uint32ti=writable_exnt;ensure_spacet4;Bigstringaf.unsafe_set_int32_let.buffert.write_posi;t.write_pos<-t.write_pos+4letwrite_uint48ti=writable_exnt;ensure_spacet6;Bigstringaf.unsafe_set_int16_let.buffert.write_posInt64.(to_inti);Bigstringaf.unsafe_set_int32_let.buffer(t.write_pos+2)Int64.(to_int32(shift_right_logicali2));t.write_pos<-t.write_pos+6letwrite_uint64ti=writable_exnt;ensure_spacet8;Bigstringaf.unsafe_set_int64_let.buffert.write_posi;t.write_pos<-t.write_pos+8letwrite_floattf=writable_exnt;ensure_spacet4;Bigstringaf.unsafe_set_int32_let.buffert.write_pos(Int32.bits_of_floatf);t.write_pos<-t.write_pos+4letwrite_doubletd=writable_exnt;ensure_spacet8;Bigstringaf.unsafe_set_int64_let.buffert.write_pos(Int64.bits_of_floatd);t.write_pos<-t.write_pos+8endletcloset=t.closed<-true;flush_buffertletis_closedt=t.closedletpending_bytest=(t.write_pos-t.scheduled_pos)+(t.bytes_received-t.bytes_written)lethas_pending_outputt=pending_bytest<>0letyieldt=t.yield<-trueletrecshift_bufferstwritten=matchBuffers.dequeue_exnt.scheduledwith|exceptionDequeue_empty->assert(written=0);ift.scheduled_pos=t.write_posthenbegint.scheduled_pos<-0;t.write_pos<-0end|{len;_}asiovec->iflen<=writtenthenbeginshift_bufferst(written-len)endelseBuffers.enqueue_front(IOVec.shiftiovecwritten)t.scheduledletrecshift_flushest~reason=matchFlushes.dequeue_exnt.flushedwith|exceptionDequeue_empty->()|(threshold,f)asflush->(* Edited notes from @dinosaure:
*
* The quantities [t.bytes_written] and [threshold] are always going to be
* positive integers. Therefore, we can treat them as unsinged integers for
* the purposes of comparision. Doing so allows us to handle overflows in
* either quantity as long as they're both within one overflow of each other.
* We can accomplish this by subracting [min_int] from both quantities before
* comparision. This shift a quantity that has not overflowed into the
* negative integer range while shifting a quantity that has overflow into
* the positive integer range.
*
* This effectively restablishes the relative difference when an overflow
* has occurred, and otherwise just compares numbers that haven't
* overflowed as similarly, just shifted down a bit.
*)ift.bytes_written-min_int>=threshold-min_intthenbeginfreason;shift_flushest~reasonendelseFlushes.enqueue_frontflusht.flushedletshift_internaltwritten~reason=shift_bufferstwritten;t.bytes_written<-t.bytes_written+written;shift_flushest~reason;;letshifttwritten=shift_internaltwritten~reason:Shiftletoperationt=ift.closedthenbegint.yield<-falseend;flush_buffert;letnothing_to_do=not(has_pending_outputt)inift.closed&¬hing_to_dothen`Closeelseift.yield||nothing_to_dothenbegint.yield<-false;`Yieldendelsebeginletiovecs=Buffers.map_to_listt.scheduled~f:(funx->x)in`Writeviovecsendletrecserializetwritev=matchoperationtwith|`Writeviovecs->beginmatchwriteviovecswith|`Okn->shifttn;ifnot(Buffers.is_emptyt.scheduled)thenyieldt|`Closed->closetend;serializetwritev|(`Close|`Yield)asnext->nextletserialize_to_stringt=closet;matchoperationtwith|`Writeviovecs->letlen=IOVec.lengthviovecsinletbytes=Bytes.createleninletpos=ref0inList.iter(function|{buffer;off;len}->Bigstringaf.unsafe_blit_to_bytesbuffer~src_off:offbytes~dst_off:!pos~len;pos:=!pos+len)iovecs;shifttlen;assert(operationt=`Close);Bytes.unsafe_to_stringbytes|`Close->""|`Yield->assertfalseletserialize_to_bigstringt=closet;matchoperationtwith|`Writeviovecs->letlen=IOVec.lengthviovecsinletbs=Bigstringaf.createleninletpos=ref0inList.iter(function|{buffer;off;len}->Bigstringaf.unsafe_blitbuffer~src_off:offbs~dst_off:!pos~len;pos:=!pos+len)iovecs;shifttlen;assert(operationt=`Close);bs|`Close->Bigstringaf.create0|`Yield->assertfalseletdrain=letreclooptacc=matchoperationtwith|`Writeviovecs->letlen=IOVec.lengthviovecsinshift_internaltlen~reason:Drain;loopt(len+acc)|`Close->acc|`Yield->looptaccinfunt->loopt0