Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix behaviour of bytes.split_multi to match string.split_multi #2364

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 19 additions & 27 deletions core/bytes/bytes.odin
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bytes

import "core:mem"
import "core:slice"
import "core:unicode"
import "core:unicode/utf8"

Expand Down Expand Up @@ -762,37 +763,28 @@ trim_suffix :: proc(s, suffix: []byte) -> []byte {
return s
}

split_multi :: proc(s: []byte, substrs: [][]byte, skip_empty := false, allocator := context.allocator) -> [][]byte #no_bounds_check {
split_multi :: proc(s: []byte, substrs: [][]byte, skip_empty := false, allocator := context.allocator) -> (result: [][]byte, err: mem.Allocator_Error) #no_bounds_check #optional_allocator_error {
if s == nil || len(substrs) <= 0 {
return nil
}

sublen := len(substrs[0])

for substr in substrs[1:] {
sublen = min(sublen, len(substr))
}

shared := len(s) - sublen

if shared <= 0 {
return nil
return nil, nil
}

// number, index, last
n, i, l := 0, 0, 0
temp_substrs := slice.clone(substrs, context.temp_allocator)
slice.sort_by(temp_substrs, proc(a, b: []byte) -> bool {
return len(a) > len(b)
})

// count results
first_pass: for i <= shared {
for substr in substrs {
if string(s[i:i+sublen]) == string(substr) {
first_pass: for i < len(s) {
for substr in temp_substrs {
if len(s) >= i + len(substr) && equal(s[i:i+len(substr)], substr) {
if !skip_empty || i - l > 0 {
n += 1
}

i += sublen
l = i

i += len(substr)
l = i
continue first_pass
}
}
Expand All @@ -807,23 +799,23 @@ split_multi :: proc(s: []byte, substrs: [][]byte, skip_empty := false, allocator

if n < 1 {
// no results
return nil
return nil, nil
}

buf := make([][]byte, n, allocator)
buf := make([][]byte, n, allocator) or_return

n, i, l = 0, 0, 0

// slice results
second_pass: for i <= shared {
for substr in substrs {
if string(s[i:i+sublen]) == string(substr) {
second_pass: for i < len(s) {
for substr in temp_substrs {
if len(s) >= i + len(substr) && equal(s[i:i+len(substr)], substr) {
if !skip_empty || i - l > 0 {
buf[n] = s[l:i]
n += 1
}

i += sublen
i += len(substr)
l = i

continue second_pass
Expand All @@ -838,7 +830,7 @@ split_multi :: proc(s: []byte, substrs: [][]byte, skip_empty := false, allocator
buf[n] = s[l:]
}

return buf
return buf, nil
}


Expand Down