VSL - The foreign.cabi.utils Structure

# Copyright 2011  Petter Urkedal
#
# This file is part of the Viz Standard Library <http://www.vizlang.org/>.
#
# The Viz Standard Library (VSL) is free software: you can redistribute it
# and/or modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# The VSL is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
# more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with the VSL.  If not, see <http://www.gnu.org/licenses/>.


# Z.  FFI Utility Functions
#
# Note:  This is not properly organized, and is subject to heavy changes.

open prelude.ubiquitous
open effect
open memory
open:c "string.h"
use cabi.stub_prefix "cviz_"

val malloc_ptrarray_init :
    int  (int  effect ψ (ptr ψ))  effect ψ (ptr ψ)

val malloc_ptrarray_of_array : array α  effect ψ (ptr ψ)

let unsafe_ptrarray_load i be unsafe_load_ptr (offset.scale i sizeof_ptr)
let unsafe_ptrarray_store i be unsafe_store_ptr (offset.scale i sizeof_ptr)

let! malloc_ptrarray_init n f
    let p do unsafe_malloc (offset.scale n sizeof_ptr)
    let! loop i
	when i < n let x do f i
		   do unsafe_ptrarray_store i p x
		   do loop (i + 1)
    do loop 0
    be p

let malloc_ptrarray_of_array xa
    be malloc_ptrarray_init (data.array.length xa)
		(i  unsafe_custom_load_ptr (data.array.get i xa))

let! unsafe_ptrarray_free_elements p n
    if n = 0 be ()
    do unsafe_ptrarray_load (n - 1) p >>= unsafe_free
    do unsafe_ptrarray_free_elements p (n - 1)

val:c strcpy_utf8_string : ptr ψ  utf8_string  effect ψ unit := "strcpy"

let! malloc_strcpy_string s
    let us be data.utf8_string.of_string s
    let n be data.utf8_string.length us
    let p do unsafe_malloc (offset.of_int (n + 1))
    do strcpy_utf8_string p us
    be p