commit a67d398a910a510700d21569dce2c7a81ae85243 parent 6f9b6114b7f61041823924dfcfea6fa05907b985 Author: Sebastian <sebastian@sebsite.pw> Date: Tue, 18 Jul 2023 18:56:03 -0400 types::c: add nulstr So C strings can be used without allocating them: use types::c; @symbol("puts") fn puts(s: *const char) int; export fn main() void = { puts(c::nulstr("hello world!\0")); }; Signed-off-by: Sebastian <sebastian@sebsite.pw> Diffstat:
M | types/c/+test.ha | | | 2 | ++ |
M | types/c/strings.ha | | | 9 | +++++++++ |
2 files changed, 11 insertions(+), 0 deletions(-)
diff --git a/types/c/+test.ha b/types/c/+test.ha @@ -21,4 +21,6 @@ let s = fromstr("hello!"); defer free(s); assert(tostr(s)! == "hello!"); + let s = nulstr("hello!\0"); + assert(tostr(s)! == "hello!"); }; diff --git a/types/c/strings.ha b/types/c/strings.ha @@ -60,3 +60,12 @@ export fn fromstr_buf(s: const str, sl: []char) *char = { return (*(&sl: *types::slice)).data: *char; }; + +// Converts a NUL-terminated Hare string to a C string. Aborts if the input +// string isn't NUL-terminated. The result is borrowed from the input. +export fn nulstr(s: const str) *const char = { + let s = &s: *types::string; + let data = s.data as *[*]u8; + assert(data[s.length - 1] == '\0', "types::c::nulstr input must be NUL-terminated"); + return s.data: *const char; +};