Skip to content

Commit 62e403a

Browse files
committed
builtin: cleanup defer blocks in string.v, reduce allocations in string.replace_char/3
1 parent 8e9f412 commit 62e403a

1 file changed

Lines changed: 4 additions & 10 deletions

File tree

‎vlib/builtin/string.v‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -455,9 +455,7 @@ pub fn (s string) replace_each(vals []string) string {
455455
// of the new string to do just one allocation.
456456
mut new_len := s.len
457457
mut idxs := []RepIndex{cap: 6}
458-
defer {
459-
unsafe { idxs.free() }
460-
}
458+
defer { unsafe { idxs.free() } }
461459
mut idx := 0
462460
s_ := s.clone()
463461
for rep_i := 0; rep_i < vals.len; rep_i += 2 {
@@ -531,7 +529,7 @@ pub fn (s string) replace_each(vals []string) string {
531529
}
532530
}
533531

534-
// replace_char replaces all occurrences of the character `rep` multiple occurrences of the character passed in `with` with respect to `repeat`.
532+
// replace_char replaces all occurrences of the character `rep`, with `repeat` x the character passed in `with`.
535533
// Example: assert '\tHello!'.replace_char(`\t`,` `,8) == ' Hello!'
536534
@[direct_array_access]
537535
pub fn (s string) replace_char(rep u8, with u8, repeat int) string {
@@ -545,10 +543,8 @@ pub fn (s string) replace_char(rep u8, with u8, repeat int) string {
545543
}
546544
// TODO: Allocating ints is expensive. Should be a stack array
547545
// - string.replace()
548-
mut idxs := []int{cap: s.len}
549-
defer {
550-
unsafe { idxs.free() }
551-
}
546+
mut idxs := []int{cap: s.len >> 2}
547+
defer { unsafe { idxs.free() } }
552548
// No need to do a contains(), it already traverses the entire string
553549
for i, ch in s {
554550
if ch == rep { // Found char? Mark its location
@@ -1001,7 +997,6 @@ pub fn (s string) split_nth(delim string, nth int) []string {
1001997
mut res := []string{}
1002998
unsafe { res.flags.set(.noslices) } // allow freeing of old data during <<
1003999
defer { unsafe { res.flags.clear(.noslices) } }
1004-
10051000
match delim.len {
10061001
0 {
10071002
for i, ch in s {
@@ -1062,7 +1057,6 @@ pub fn (s string) rsplit_nth(delim string, nth int) []string {
10621057
mut res := []string{}
10631058
unsafe { res.flags.set(.noslices) } // allow freeing of old data during <<
10641059
defer { unsafe { res.flags.clear(.noslices) } }
1065-
10661060
match delim.len {
10671061
0 {
10681062
for i := s.len - 1; i >= 0; i-- {

0 commit comments

Comments
 (0)