hare

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

commit d56e1c8cbaaae927c1819bdf098d801aa00eb532
parent 1f93912e076d740d306ee615f3159fc93367390e
Author: Drew DeVault <sir@cmpwn.com>
Date:   Mon, 13 Nov 2023 10:55:41 +0100

types::c: add unterminatedstr

This converts a Hare string into a non-NUL-terminated C string.

Signed-off-by: Drew DeVault <sir@cmpwn.com>

Diffstat:
Mtypes/c/strings.ha | 19+++++++++++++++++++
1 file changed, 19 insertions(+), 0 deletions(-)

diff --git a/types/c/strings.ha b/types/c/strings.ha @@ -4,6 +4,11 @@ use encoding::utf8; use types; +let empty: [_]u8 = [0]; + +// An empty NUL-terminated C string. +export let empty_string: *const char = &empty[0]: *const char; + // Computes the length of a NUL-terminated C string, in octets, in O(n). The // computed length does not include the NUL terminator. export fn strlen(cstr: *const char) size = { @@ -72,3 +77,17 @@ export fn nulstr(s: const str) *const char = { assert(data[s.length - 1] == '\0', "types::c::nulstr input must be NUL-terminated"); return s.data: *const char; }; + +// Converts a non-NUL-terminated Hare string to a C string. The return value is +// borrowed from the input, except in the case of an empty string, in which case +// it is statically allocated. +// +// Use with caution! +export fn unterminatedstr(s: const str) *const char = { + let s = &s: *types::string; + if (s.data == null) { + return empty_string; + }; + let data = s.data as *[*]u8; + return data: *const char; +};