From: Brendan Hansen Date: Sat, 19 Aug 2023 01:31:31 +0000 (-0500) Subject: added: string.to_cstr_on_stack X-Git-Url: https://git.brendanfh.com/?a=commitdiff_plain;h=651a01ac096ad4974ea53ffbcc190bb682d39f32;p=onyx.git added: string.to_cstr_on_stack --- diff --git a/CHANGELOG b/CHANGELOG index 0cd2beb7..92f0e157 100644 --- 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: diff --git a/core/string/string.onyx b/core/string/string.onyx index a1b89a40..29a259a1 100644 --- a/core/string/string.onyx +++ b/core/string/string.onyx @@ -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 {}