bytes: restore old Trim/TrimLeft behavior for nil

Keep returning nil for the cases where we historically returned nil,
even though this is slightly different for TrimLeft and TrimRight.

Fixes #51793

Change-Id: Ifbdfc6b09d52b8e063cfe6341019f9b2eb8b70e9
Reviewed-on: https://go-review.googlesource.com/c/go/+/393876
Trust: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
This commit is contained in:
Ian Lance Taylor 2022-03-18 12:14:20 -07:00
parent 460fd63ccc
commit 32fdad19a2
2 changed files with 106 additions and 11 deletions

View file

@ -909,7 +909,11 @@ func containsRune(s string, r rune) bool {
// Trim returns a subslice of s by slicing off all leading and
// trailing UTF-8-encoded code points contained in cutset.
func Trim(s []byte, cutset string) []byte {
if len(s) == 0 || cutset == "" {
if len(s) == 0 {
// This is what we've historically done.
return nil
}
if cutset == "" {
return s
}
if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
@ -924,7 +928,11 @@ func Trim(s []byte, cutset string) []byte {
// TrimLeft returns a subslice of s by slicing off all leading
// UTF-8-encoded code points contained in cutset.
func TrimLeft(s []byte, cutset string) []byte {
if len(s) == 0 || cutset == "" {
if len(s) == 0 {
// This is what we've historically done.
return nil
}
if cutset == "" {
return s
}
if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
@ -940,6 +948,10 @@ func trimLeftByte(s []byte, c byte) []byte {
for len(s) > 0 && s[0] == c {
s = s[1:]
}
if len(s) == 0 {
// This is what we've historically done.
return nil
}
return s
}
@ -950,6 +962,10 @@ func trimLeftASCII(s []byte, as *asciiSet) []byte {
}
s = s[1:]
}
if len(s) == 0 {
// This is what we've historically done.
return nil
}
return s
}
@ -964,6 +980,10 @@ func trimLeftUnicode(s []byte, cutset string) []byte {
}
s = s[n:]
}
if len(s) == 0 {
// This is what we've historically done.
return nil
}
return s
}