aboutsummaryrefslogtreecommitdiff
path: root/core/strings
diff options
context:
space:
mode:
authorFeoramund <161657516+Feoramund@users.noreply.github.com>2025-02-27 18:48:15 -0500
committerFeoramund <161657516+Feoramund@users.noreply.github.com>2025-02-27 18:54:38 -0500
commitb2e3b34ce0bc46dfa80046f13275812c0ec15a80 (patch)
tree70f1cd39e5ca8bd3a5ee91b9e3e3b36e567d150d /core/strings
parent94152ca701929d877d0ca94f922ba29fbafd46f3 (diff)
Fix #4890
`strings.to_cstring` previously would not check if the buffer could handle the extra null byte and could lead to segmentation violations when using the resulting string in an API expecting the terminator.
Diffstat (limited to 'core/strings')
-rw-r--r--core/strings/builder.odin25
1 files changed, 24 insertions, 1 deletions
diff --git a/core/strings/builder.odin b/core/strings/builder.odin
index 97a615990..e5a88527a 100644
--- a/core/strings/builder.odin
+++ b/core/strings/builder.odin
@@ -288,18 +288,41 @@ to_string :: proc(b: Builder) -> (res: string) {
/*
Appends a trailing null byte after the end of the current Builder byte buffer and then casts it to a cstring
+NOTE: This procedure will not check if the backing buffer has enough space to include the extra null byte.
+
Inputs:
- b: A pointer to builder
Returns:
- res: A cstring of the Builder's buffer
*/
-to_cstring :: proc(b: ^Builder) -> (res: cstring) {
+unsafe_to_cstring :: proc(b: ^Builder) -> (res: cstring) {
append(&b.buf, 0)
pop(&b.buf)
return cstring(raw_data(b.buf))
}
/*
+Appends a trailing null byte after the end of the current Builder byte buffer and then casts it to a cstring
+
+Inputs:
+- b: A pointer to builder
+
+Returns:
+- res: A cstring of the Builder's buffer upon success
+- err: An optional allocator error if one occured, `nil` otherwise
+*/
+to_cstring :: proc(b: ^Builder) -> (res: cstring, err: mem.Allocator_Error) {
+ n := append(&b.buf, 0) or_return
+ if n != 1 {
+ return nil, .Out_Of_Memory
+ }
+ pop(&b.buf)
+ #no_bounds_check {
+ assert(b.buf[len(b.buf)] == 0)
+ }
+ return cstring(raw_data(b.buf)), nil
+}
+/*
Returns the length of the Builder's buffer, in bytes
Inputs: