Skip to content

Commit

Permalink
performance optimisations
Browse files Browse the repository at this point in the history
  • Loading branch information
spytheman committed May 25, 2024
1 parent ff51168 commit 6209c09
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions vlib/builtin/string.v
Original file line number Diff line number Diff line change
Expand Up @@ -927,7 +927,7 @@ pub fn (s string) split_nth(delim string, nth int) []string {
0 {
for i, ch in s {
if nth > 0 && res.len == nth - 1 {
res << s[i..]
res << unsafe { s.substr_unsafe(i, s.len - 1) }
break
}
res << ch.ascii_str()
Expand All @@ -941,7 +941,7 @@ pub fn (s string) split_nth(delim string, nth int) []string {
if nth > 0 && res.len == nth - 1 {
break
}
res << s.substr(start, i)
res << unsafe { s.substr_unsafe(start, i) }
start = i + 1
}
}
Expand All @@ -953,18 +953,18 @@ pub fn (s string) split_nth(delim string, nth int) []string {
mut start := 0
// Add up to `nth` segments left of every occurrence of the delimiter.
for i := 0; i <= s.len; i++ {
if s[i..i + delim.len] or { break } == delim {
if i + delim.len <= s.len && unsafe { s.substr_unsafe(i, i + delim.len) } == delim {
if nth > 0 && res.len == nth - 1 {
break
}
res << s.substr(start, i)
res << unsafe { s.substr_unsafe(start, i) }
i += delim.len
start = i
}
}
// Then add the remaining part of the string as the last segment.
if nth < 1 || res.len < nth {
res << s[start..]
res << unsafe { s.substr_unsafe(start, s.len - 1) }
}
}
}
Expand All @@ -984,7 +984,7 @@ pub fn (s string) rsplit_nth(delim string, nth int) []string {
0 {
for i := s.len - 1; i >= 0; i-- {
if nth > 0 && res.len == nth - 1 {
res << s[..i + 1]
res << unsafe { s.substr_unsafe(0, i + 1) }
break
}
res << s[i].ascii_str()
Expand All @@ -998,29 +998,30 @@ pub fn (s string) rsplit_nth(delim string, nth int) []string {
if nth > 0 && res.len == nth - 1 {
break
}
res << s[i + 1..rbound]
res << unsafe { s.substr_unsafe(i + 1, rbound) }
rbound = i
}
}
if nth < 1 || res.len < nth {
res << s[..rbound]
res << unsafe { s.substr_unsafe(0, rbound) }
}
}
else {
mut rbound := s.len
for i := s.len - 1; i >= 0; i-- {
is_delim := i - delim.len >= 0 && s[i - delim.len..i] == delim
is_delim := i - delim.len >= 0
&& unsafe { s.substr_unsafe(i - delim.len, i) } == delim
if is_delim {
if nth > 0 && res.len == nth - 1 {
break
}
res << s[i..rbound]
res << unsafe { s.substr_unsafe(i, rbound) }
i -= delim.len
rbound = i
}
}
if nth < 1 || res.len < nth {
res << s[..rbound]
res << unsafe { s.substr_unsafe(0, rbound) }
}
}
}
Expand Down

0 comments on commit 6209c09

Please sign in to comment.