1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980(*{{{ 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;Somesletreadxn=matchread_exactly'xnwith|Nonewhenx.pos>=x.len->raiseEnd_of_file|None->return(read_restx)|Somex->returnxletwritexs=Buffer.add_stringxs;return()letflush_x=return()end