~sircmpwn/hare-dev

hare: types::c: add fromstr_nul v2 SUPERSEDED

Sebastian: 1
 types::c: add fromstr_nul

 1 files changed, 9 insertions(+), 0 deletions(-)
#1003015 alpine.yml success
#1003016 freebsd.yml success
Export patchset (mbox)
How do I use this?

Copy & paste the following snippet into your terminal to import this patchset into git:

curl -s https://lists.sr.ht/~sircmpwn/hare-dev/patches/41700/mbox | git am -3
Learn more about email & git

[PATCH hare v2] types::c: add fromstr_nul Export this patch

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
hare/patches: SUCCESS in 1m41s

[types::c: add fromstr_nul][0] v2 from [Sebastian][1]

[0]: https://lists.sr.ht/~sircmpwn/hare-dev/patches/41700
[1]: mailto:sebastian@sebsite.pw

✓ #1003016 SUCCESS hare/patches/freebsd.yml https://builds.sr.ht/~sircmpwn/job/1003016
✓ #1003015 SUCCESS hare/patches/alpine.yml  https://builds.sr.ht/~sircmpwn/job/1003015
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?