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::fromstr_nul("hello world!\0"));
};
Signed-off-by: Sebastian <sebastian@sebsite.pw>
---
v2: fix commit message (accidentally used printf instead of puts when
calling), and removed strings::hassuffix in favor of indexing directly
types/c/strings.ha | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/types/c/strings.ha b/types/c/strings.ha
index dce99c3c..b37fd1d6 100644
--- 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 fromstr_nul(s: const str) *const char = {+ let s = &s: *types::string;+ let data = s.data as *[*]u8;+ assert(data[s.length - 1] == '\0', "types::c::fromstr_nul input must be NUL-terminated");+ return s.data: *const char;+};
--
2.40.1
I was thinking that it might make sense to have this symbol name be much
shorter, since it's going to be used all the time in programs which have
to interop with C.
c::string("hello\0")
c::str0("hello\0")
c::strnul("hello\0")
c::cstr("hello\0")
The latter might be nice if you do:
use c::{cstr};
printf(cstr("Hello %s!\0"), cstr("world\0"));
other ideas?