Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] string buffer as (in|out)_channel
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Issac Trotts <ijtrotts@u...>
Subject: Re: [Caml-list] string buffer as (in|out)_channel
Chris Hecker wrote:

>
> Is there any way to do something similar to the C++ string stream 
> stuff, where you treat strings (or Buffer.t's) as in_ or 
> out_channels?  The Format module has a formatter for strings, but 
> there doesn't seem to be a way to do it with Pervasives.  Something like:
>
> val out_channel_of_buffer : Buffer.t -> out_channel
> val in_channel_of_buffer : Buffer.t -> in_channel
>
> and maybe _of_string versions too (probably necessary because you 
> can't convert a string to a buffer for the in_channel), which fill up 
> and don't expand.
>
> It'd be very useful to be able to do this. 


Please disregard the previous buggy message I sent out.  Here's a 
fixed-up version:

(* read from a Buffer via a Stream *)
let stream_of_buffer buf =
  Stream.from
    (fun i ->
      let s = Buffer.contents buf in
      if i >= String.length s then None else Some s.[i]
    )

(* write to buffers and other things without knowing what they are *)
module Ostream :
  sig
    type t
    val of_function : (char -> unit) -> t
    val of_buffer : Buffer.t -> t
    val of_string : string -> t
    val of_out_channel : out_channel -> t
    val output_char : t -> char -> unit
    val output_string : t -> string -> unit
    val output_value : t -> 'a -> unit
  end
    =
  struct
    type t = char -> unit

    let of_function f = f

    let of_buffer (buf:Buffer.t) : t =
      fun (c:char) -> Buffer.add_char buf c

    let of_string (s:string) : t =
      let i = ref 0 in
      fun (c:char) -> s.[!i] <- c; incr i

    let of_out_channel (chan:out_channel) : t =
      fun (c:char) -> output_char chan c

    let output_char (ostream:t) (c:char) : unit =
      ostream c

    let output_string (ostream:t) (str:string) =
      String.iter ostream str
   
    let output_value (ostream:t) thing =
      let str = Marshal.to_string thing [] in
      output_string ostream str
     
  end


Issac








>
>
> Thanks,
> Chris
>
> PS.  Please cc me on replies, I temporarily unsubscribed from the 
> list, thanks!
>
> -------------------
> To unsubscribe, mail caml-list-request@inria.fr Archives: 
> http://caml.inria.fr
> Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: 
> http://caml.inria.fr/FAQ/
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
>
>


-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners