diff --git a/lib/std/core/string.c3 b/lib/std/core/string.c3 index d256a2e9d..310963f7f 100644 --- a/lib/std/core/string.c3 +++ b/lib/std/core/string.c3 @@ -1,5 +1,7 @@ module std::core::string; import std::io, std::ascii; +import std::core::mem::allocator; + typedef String @if(!$defined(String)) = inline char[]; @@ -96,7 +98,8 @@ fn ZString tformat_zstr(String fmt, args...) @format(0) } <* - Return a new String created using the formatting function. + Return a new String created using the formatting function, this function will implicitly + use the temp allocator. @param [inout] allocator : `The allocator to use` @param [in] fmt : `The formatting string` @@ -156,29 +159,34 @@ macro bool char_in_set(char c, String set) return false; } +<* + @return "a String which is safe to convert to a ZString" +*> fn String join(Allocator allocator, String[] s, String joiner) { if (!s) { return (String)allocator::new_array(allocator, char, 2)[:0]; } - - usz total_size = joiner.len * s.len; + usz joiner_len = joiner.len; + usz total_size = joiner_len * (s.len - 1) + 1; foreach (String* &str : s) { total_size += str.len; } - @pool() + char[] data = allocator::alloc_array(allocator, char, total_size); + usz offset = s[0].len; + data[:offset] = s[0][:offset]; + foreach (String* &str : s[1..]) { - DString res = dstring::temp_with_capacity(total_size); - res.append(s[0]); - foreach (String* &str : s[1..]) - { - res.append(joiner); - res.append(*str); - } - return res.copy_str(allocator); + data[offset:joiner_len] = joiner[:joiner_len]; + offset += joiner_len; + usz len = str.len; + data[offset:len] = str.[:len]; + offset += len; }; + data[offset] = 0; + return (String)data[:offset]; } <* diff --git a/releasenotes.md b/releasenotes.md index 45452f692..4b8ea5079 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -7,6 +7,7 @@ ### Stdlib changes - Summarize sort macros as generic function wrappers to reduce the amount of generated code. #2831 +- Remove dependency on temp allocator in String.join. ### Fixes - Add error message if directory with output file name already exists