strings, bytes: add CutPrefix and CutSuffix

Fixes #42537

Change-Id: Ie03c2614ffee30ebe707acad6b9f6c28fb134a45
Reviewed-on: https://go-review.googlesource.com/c/go/+/407176
Reviewed-by: Benny Siegert <bsiegert@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Changkun Ou <mail@changkun.de>
Reviewed-by: Ian Lance Taylor <iant@google.com>
This commit is contained in:
Changkun Ou 2022-05-19 11:57:50 +02:00 committed by Robert Griesemer
parent 0df7ad2e79
commit 68005592b3
5 changed files with 136 additions and 0 deletions

View file

@ -1700,6 +1700,48 @@ func TestCut(t *testing.T) {
}
}
var cutPrefixTests = []struct {
s, sep string
after string
found bool
}{
{"abc", "a", "bc", true},
{"abc", "abc", "", true},
{"abc", "", "abc", true},
{"abc", "d", "abc", false},
{"", "d", "", false},
{"", "", "", true},
}
func TestCutPrefix(t *testing.T) {
for _, tt := range cutPrefixTests {
if after, found := CutPrefix([]byte(tt.s), []byte(tt.sep)); string(after) != tt.after || found != tt.found {
t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found)
}
}
}
var cutSuffixTests = []struct {
s, sep string
after string
found bool
}{
{"abc", "bc", "a", true},
{"abc", "abc", "", true},
{"abc", "", "abc", true},
{"abc", "d", "abc", false},
{"", "d", "", false},
{"", "", "", true},
}
func TestCutSuffix(t *testing.T) {
for _, tt := range cutSuffixTests {
if after, found := CutSuffix([]byte(tt.s), []byte(tt.sep)); string(after) != tt.after || found != tt.found {
t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found)
}
}
}
func TestBufferGrowNegative(t *testing.T) {
defer func() {
if err := recover(); err == nil {