aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorgingerBill <gingerBill@users.noreply.github.com>2025-12-21 15:21:26 +0000
committergingerBill <gingerBill@users.noreply.github.com>2025-12-21 15:21:26 +0000
commitca20a9c8e78df9e0d483589ec58300d05d92b425 (patch)
treeb81d393b0e24357dcc64de6d3d191e75d918e85d
parente138e76f21532527726897421b139fde9d05e7ce (diff)
Pre`reserve` the memory needed for `strings.builder_replace`
-rw-r--r--core/strings/builder.odin37
1 files changed, 36 insertions, 1 deletions
diff --git a/core/strings/builder.odin b/core/strings/builder.odin
index da9b6df27..ce636a2a1 100644
--- a/core/strings/builder.odin
+++ b/core/strings/builder.odin
@@ -880,6 +880,20 @@ builder_replace :: proc(b: ^Builder, old, new: string, n: int, loc := #caller_lo
}
if len(old) == 0 {
+ // NOTE(bill): reserve the necessary memory
+ found := 0
+ for i := 0; i <= len(b.buf); i += len(new)+1 {
+ if n > 0 && found == n {
+ break
+ }
+ found += 1
+ }
+ if found == 0 {
+ return
+ }
+ reserve(&b.buf, len(b.buf) + len(new)*found) or_return
+
+
for i := 0; i <= len(b.buf); i += len(new)+1 {
if n > 0 && replaced == n {
break
@@ -891,6 +905,27 @@ builder_replace :: proc(b: ^Builder, old, new: string, n: int, loc := #caller_lo
replaced += 1
}
} else {
+ if len(new) > len(old) {
+ // NOTE(bill): reserve the necessary memory
+ found := 0
+ for i := 0; i < len(b.buf); /**/ {
+ if n > 0 && found == n {
+ break
+ }
+
+ j := index(string(b.buf[i:]), old)
+ if j < 0 {
+ break
+ }
+ i += j+len(old)
+ found += 1
+ }
+ if found == 0 {
+ return
+ }
+ reserve(&b.buf, len(b.buf) + (len(new)-len(old))*found) or_return
+ }
+
for i := 0; i < len(b.buf); /**/ {
if n > 0 && replaced == n {
break
@@ -901,7 +936,7 @@ builder_replace :: proc(b: ^Builder, old, new: string, n: int, loc := #caller_lo
break
}
- if len(new) >= len(old) {
+ if len(new) > len(old) {
resize(&b.buf, len(b.buf) + len(new)-len(old)) or_return
}