fix: utils.TrimBytes should trim all content (#1779)

* perf: if all string content should be trimmed, end the loop early

* test: complete test cases for all Trim functions

* fix: utils.TrimBytes should trim all content
pull/1780/head
Fufu 2022-02-15 14:57:51 +08:00 committed by GitHub
parent e1833df93c
commit 7b1a7a9513
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 48 additions and 3 deletions

View File

@ -41,7 +41,7 @@ func TrimLeftBytes(b []byte, cutset byte) []byte {
// TrimBytes is the equivalent of bytes.Trim
func TrimBytes(b []byte, cutset byte) []byte {
i, j := 0, len(b)-1
for ; i < j; i++ {
for ; i <= j; i++ {
if b[i] != cutset {
break
}

View File

@ -80,6 +80,15 @@ func Test_TrimRightBytes(t *testing.T) {
res = TrimRightBytes([]byte("/test"), '/')
AssertEqual(t, []byte("/test"), res)
res = TrimRightBytes([]byte(" "), ' ')
AssertEqual(t, 0, len(res))
res = TrimRightBytes([]byte(" "), ' ')
AssertEqual(t, 0, len(res))
res = TrimRightBytes([]byte(""), ' ')
AssertEqual(t, 0, len(res))
}
func Benchmark_TrimRightBytes(b *testing.B) {
@ -106,6 +115,15 @@ func Test_TrimLeftBytes(t *testing.T) {
res = TrimLeftBytes([]byte("test/"), '/')
AssertEqual(t, []byte("test/"), res)
res = TrimLeftBytes([]byte(" "), ' ')
AssertEqual(t, 0, len(res))
res = TrimLeftBytes([]byte(" "), ' ')
AssertEqual(t, 0, len(res))
res = TrimLeftBytes([]byte(""), ' ')
AssertEqual(t, 0, len(res))
}
func Benchmark_TrimLeftBytes(b *testing.B) {
@ -135,6 +153,15 @@ func Test_TrimBytes(t *testing.T) {
res = TrimBytes([]byte(".test"), '.')
AssertEqual(t, []byte("test"), res)
res = TrimBytes([]byte(" "), ' ')
AssertEqual(t, 0, len(res))
res = TrimBytes([]byte(" "), ' ')
AssertEqual(t, 0, len(res))
res = TrimBytes([]byte(""), ' ')
AssertEqual(t, 0, len(res))
}
func Benchmark_TrimBytes(b *testing.B) {

View File

@ -38,12 +38,12 @@ func TrimLeft(s string, cutset byte) string {
// Trim is the equivalent of strings.Trim
func Trim(s string, cutset byte) string {
i, j := 0, len(s)-1
for ; i < j; i++ {
for ; i <= j; i++ {
if s[i] != cutset {
break
}
}
for ; i <= j; j-- {
for ; i < j; j-- {
if s[j] != cutset {
break
}

View File

@ -71,6 +71,15 @@ func Test_TrimRight(t *testing.T) {
res = TrimRight("/test", '/')
AssertEqual(t, "/test", res)
res = TrimRight(" ", ' ')
AssertEqual(t, "", res)
res = TrimRight(" ", ' ')
AssertEqual(t, "", res)
res = TrimRight("", ' ')
AssertEqual(t, "", res)
}
func Benchmark_TrimRight(b *testing.B) {
@ -97,6 +106,15 @@ func Test_TrimLeft(t *testing.T) {
res = TrimLeft("test/", '/')
AssertEqual(t, "test/", res)
res = TrimLeft(" ", ' ')
AssertEqual(t, "", res)
res = TrimLeft(" ", ' ')
AssertEqual(t, "", res)
res = TrimLeft("", ' ')
AssertEqual(t, "", res)
}
func Benchmark_TrimLeft(b *testing.B) {