From d92f9e77b00601cb6d1dc8460696c1c9c3c73b34 Mon Sep 17 00:00:00 2001 From: shadowninja55 <49539636+shadowninja55@users.noreply.github.com> Date: Tue, 16 Mar 2021 14:30:27 -0400 Subject: [PATCH] builtin.string: optimize string.split_nth() for len == 1 delim (#9325) --- vlib/builtin/string.v | 88 +++++++++++++++++++++++++++++-------------- 1 file changed, 59 insertions(+), 29 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index cc6da37970..e37491c81b 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -530,40 +530,70 @@ pub fn (s string) split(delim string) []string { pub fn (s string) split_nth(delim string, nth int) []string { mut res := []string{} mut i := 0 - if delim.len == 0 { - i = 1 - for ch in s { - if nth > 0 && i >= nth { - res << s[i..] - break + + match delim.len { + 0 { + i = 1 + for ch in s { + if nth > 0 && i >= nth { + res << s[i..] + break + } + res << ch.ascii_str() + i++ } - res << ch.ascii_str() - i++ + return res } - return res - } - mut start := 0 - // Take the left part for each delimiter occurence - for i <= s.len { - is_delim := i + delim.len <= s.len && s.substr(i, i + delim.len) == delim - if is_delim { - val := s.substr(start, i) - was_last := nth > 0 && res.len == nth - 1 - if was_last { - break + 1 { + mut start := 0 + delim_byte := delim[0] + + for i < s.len { + if s[i] == delim_byte { + was_last := nth > 0 && res.len == nth - 1 + if was_last { + break + } + val := s.substr(start, i) + res << val + start = i + delim.len + i = start + } else { + i++ + } } - res << val - start = i + delim.len - i = start - } else { - i++ + + // Then the remaining right part of the string + if nth < 1 || res.len < nth { + res << s[start..] + } + return res + } + else { + mut start := 0 + // Take the left part for each delimiter occurence + for i <= s.len { + is_delim := i + delim.len <= s.len && s.substr(i, i + delim.len) == delim + if is_delim { + was_last := nth > 0 && res.len == nth - 1 + if was_last { + break + } + val := s.substr(start, i) + res << val + start = i + delim.len + i = start + } else { + i++ + } + } + // Then the remaining right part of the string + if nth < 1 || res.len < nth { + res << s[start..] + } + return res } } - // Then the remaining right part of the string - if nth < 1 || res.len < nth { - res << s[start..] - } - return res } // split_into_lines splits the string by newline characters.