123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687(*{{{ Copyright (c) 2014 Andy Ray
* Copyright (c) 2014 Anil Madhavapeddy <anil@recoil.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)(* input channel type - a string with a (file) position and length *)typebuf={str:string;mutablepos:int;len:int}letopen_instr={str;pos=0;len=String.lengthstr}moduleM=structtype'at='aletreturna=atypeconn=buflet(>>=)=(|>)typeic=buf(* output channels are just buffers *)typeoc=Buffer.t(* the following read/write logic has only been lightly tested... *)letread_restx=lets=String.subx.strx.pos(x.len-x.pos)inx.pos<-x.len;sletread_line'x=ifx.pos<x.lenthenletstart=x.posintrywhilex.str.[x.pos]!='\n'dox.pos<-x.pos+1done;letl=ifx.pos>0&&x.str.[x.pos-1]='\r'thenx.pos-start-1elsex.pos-startinlets=String.subx.strstartlinx.pos<-x.pos+1;Someswith_->Some(read_restx)elseNoneletread_linex=return(read_line'x)letread_exactly'xn=ifx.len-x.pos<nthenNoneelselets=String.subx.strx.posninx.pos<-x.pos+n;Somesletrefill_=`Eofletwith_input_buffert~f=letres,count=ft.str~pos:t.pos~len:(t.len-t.pos)int.pos<-t.pos+count;resletreadxn=matchread_exactly'xnwith|Nonewhenx.pos>=x.len->raiseEnd_of_file|None->return(read_restx)|Somex->returnxletwritexs=Buffer.add_stringxs;return()letflush_x=return()end