added: string.to_cstr_on_stack
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Sat, 19 Aug 2023 01:31:31 +0000 (20:31 -0500)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Sat, 19 Aug 2023 01:31:31 +0000 (20:31 -0500)
CHANGELOG
core/string/string.onyx

index 0cd2beb7a93da69ef81975b5fd1783bc4b0d4b03..92f0e157209aef66e898cfade7004c687ea124d4 100644 (file)
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -6,6 +6,7 @@ Additions:
 * Tagging global variables.
     - Just like procedure and structure tags.
     - Use `runtime.info.tagged_globals` and `runtime.info.get_globals_with_tag()`
+* `string.to_cstr_on_stack`
 
 Removals:
 
index a1b89a402560d600ef383614a26639c702b598e1..29a259a1185faaa1984c02ed223bc9ca641aab02 100644 (file)
@@ -51,6 +51,25 @@ from_cstr :: (s: cstr) -> str {
     return .{ data = s, count = length(s) };
 }
 
+#doc """
+    Converts a `str` into a `cstr` by copying the memory of the string to the stack,
+    with an additional byte at the end that is set to 0, to correctly for a C-string.
+
+    This only needs to be done when the string does not contain a `\0` byte on the end,
+    which is most of the time. If you know that the string has a `\0` byte, simply use `s.data`.
+"""
+to_cstr_on_stack :: macro (s_: str) -> cstr {
+    use core.alloc
+    use core.memory
+
+    s := s_;
+    result := alloc.from_stack(sizeof u8 * (s.count + 1));
+    memory.set(result, 0, s.count + 1);
+    memory.copy(result, s.data, s.count);
+
+    return result;
+}
+
 
 length :: #match #local {}