hare

The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

commit fb59d6db4e6cba353218c300a24cbd23bcacb21d
parent 82819789e4405858c38d51688c660a7ed0ab220b
Author: Drew DeVault <sir@cmpwn.com>
Date:   Tue,  2 Mar 2021 15:16:39 -0500

strings: add strings::to_c

Diffstat:
Mstrings/cstrings.ha | 14++++++++++++++
1 file changed, 14 insertions(+), 0 deletions(-)

diff --git a/strings/cstrings.ha b/strings/cstrings.ha @@ -1,5 +1,6 @@ use encoding::utf8; use types; +use rt; let emptybuf: [1]u8 = [0]; @@ -35,3 +36,16 @@ export fn from_c(cstr: *const char) const str = { assert(utf8::valid(s)); return s; }; + +// Converts a Hare string to a C string. The result is allocated, the caller +// must free it when they're done. +export fn to_c(s: const str) *char = { + let ptr = rt::malloc(len(s) + 1): nullable *[*]u8; + let ptr = match (ptr) { + null => abort("Out of memory"), + p: *[*]u8 => p, + }; + rt::memcpy(ptr, (&s: *types::string).data, len(s)); + ptr[len(s)] = 0; + return ptr: *char; +};