Skip to content

Commit

Permalink
✨ feat: byteutil - add new util func Cut() for split []byte
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed May 30, 2023
1 parent 359d163 commit d3c8d4b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions byteutil/byteutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,13 @@ func AppendAny(dst []byte, v any) []byte {
}
return dst
}

// Cut bytes. like the strings.Cut()
func Cut(bs []byte, sep byte) (before, after []byte, found bool) {
if i := bytes.IndexByte(bs, sep); i >= 0 {
return bs[:i], bs[i+1:], true
}

before = bs
return
}
13 changes: 13 additions & 0 deletions byteutil/byteutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,16 @@ func TestAppendAny(t *testing.T) {
assert.Eq(t, []byte("1<nil>"), byteutil.AppendAny([]byte("1"), nil))
assert.Eq(t, "3600000000000", string(byteutil.AppendAny([]byte{}, timex.OneHour)))
}

func TestCut(t *testing.T) {
// test for byteutil.Cut()
b, a, ok := byteutil.Cut([]byte("age=123"), '=')
assert.True(t, ok)
assert.Eq(t, []byte("age"), b)
assert.Eq(t, []byte("123"), a)

b, a, ok = byteutil.Cut([]byte("age=123"), 'x')
assert.False(t, ok)
assert.Eq(t, []byte("age=123"), b)
assert.Empty(t, a)
}

0 comments on commit d3c8d4b

Please sign in to comment.