bytes, strings: add Cut

Using Cut is a clearer way to write the vast majority (>70%)
of existing code that calls Index, IndexByte, IndexRune, and SplitN.
There is more discussion on https://golang.org/issue/46336.

Fixes #46336.

Change-Id: Ia418ed7c3706c65bf61e1b2c5baf534cb783e4d3
Reviewed-on: https://go-review.googlesource.com/c/go/+/351710
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
This commit is contained in:
Russ Cox 2021-09-21 10:59:16 -04:00
parent 810b08b8ec
commit 8e36ab0551
6 changed files with 179 additions and 91 deletions

View file

@ -1567,6 +1567,29 @@ func TestEqualFold(t *testing.T) {
}
}
var cutTests = []struct {
s, sep string
before, after string
found bool
}{
{"abc", "b", "a", "c", true},
{"abc", "a", "", "bc", true},
{"abc", "c", "ab", "", true},
{"abc", "abc", "", "", true},
{"abc", "", "", "abc", true},
{"abc", "d", "abc", "", false},
{"", "d", "", "", false},
{"", "", "", "", true},
}
func TestCut(t *testing.T) {
for _, tt := range cutTests {
if before, after, found := Cut([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || string(after) != tt.after || found != tt.found {
t.Errorf("Cut(%q, %q) = %q, %q, %v, want %q, %q, %v", tt.s, tt.sep, before, after, found, tt.before, tt.after, tt.found)
}
}
}
func TestBufferGrowNegative(t *testing.T) {
defer func() {
if err := recover(); err == nil {