Home My Page Projects Code Snippets Project Openings 3D graphics for Standard ML
Summary Activity SCM

SCM Repository

[sml3d] View of /trunk/sml3d/src/raw-data/c-string.sml
ViewVC logotype

View of /trunk/sml3d/src/raw-data/c-string.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 659 - (download) (annotate)
Sat Jan 2 04:50:37 2010 UTC (10 years, 1 month ago) by jhr
File size: 1900 byte(s)
  Factor out support for low-level C data into separate library.  This library
  is used by both the OpenCL and OpenGL libraries.
(* c-string.sml
 *
 * COPYRIGHT (c) 2006 John Reppy (http://www.cs.uchicago.edu/~jhr)
 * All rights reserved.
 *
 * Utility code for manipulating C strings.  Use these operations
 * with care, since ill-formed C strings can cause bad things (TM)
 * to happen.
 *)

signature C_STRING =
  sig
    type c_string = MLton.Pointer.t

  (* the length of a null-terminated C string *)
    val strlen : c_string -> int

    val toML : c_string -> string option

  (* given a contiguous sequence of strings terminated by an empty string,
   * convert them to a list of SML strings.
   *)
    val cstringsToML : c_string -> string list

  (* allocate an initialize a string in the C heap *)
    val allocString : string -> c_string

  end

structure CString : C_STRING =
  struct

    type c_string = MLton.Pointer.t

    fun getChar (s, i) = Byte.byteToChar (MLton.Pointer.getWord8 (s, i))

    fun strlen s = let
	  fun lp n = if getChar(s, n) = #"\000" then n else lp(n+1)
	  in
	    lp 0
	  end

  (* convert an C pointer to an SML string value *)
    fun toML (s : c_string) = if (s = MLton.Pointer.null)
	  then NONE
	  else SOME(CharVector.tabulate (strlen s, fn i => getChar (s, i)))

  (* given a contiguous sequence of strings terminated by an empty string,
   * convert them to a list of SML strings.
   *)
    fun cstringsToML (s : c_string) = let
	  fun lp p = let
		val n = strlen p
		in
		  if (n = 0) then []
		  else let
		    val s = CharVector.tabulate (n, fn i => getChar (s, i))
		    in
		      s :: lp(MLton.Pointer.add(p, Word.fromInt(n+1)))
		    end
		end
	  in
	    lp s
	  end

  (* allocate an initialize a string in the C heap *)
    fun allocString s = let
	  val ptr = CAlloc.malloc(C_Size.fromInt(size s + 1))
	  in
	    CharVector.appi (fn (i, c) => MLton.Pointer.setWord8 (ptr, i, Byte.charToByte c)) s;
	    MLton.Pointer.setWord8 (ptr, size s, 0w0);
	    ptr
	  end

  end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0