From d3c8d4b3c4950d2a3d5336c1f671b846c8482741 Mon Sep 17 00:00:00 2001 From: Inhere Date: Wed, 31 May 2023 01:00:18 +0800 Subject: [PATCH] :sparkles: feat: byteutil - add new util func Cut() for split []byte --- byteutil/byteutil.go | 10 ++++++++++ byteutil/byteutil_test.go | 13 +++++++++++++ 2 files changed, 23 insertions(+) diff --git a/byteutil/byteutil.go b/byteutil/byteutil.go index dc2d50f19..45c394556 100644 --- a/byteutil/byteutil.go +++ b/byteutil/byteutil.go @@ -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 +} diff --git a/byteutil/byteutil_test.go b/byteutil/byteutil_test.go index 4d6b161aa..344dcebf7 100644 --- a/byteutil/byteutil_test.go +++ b/byteutil/byteutil_test.go @@ -41,3 +41,16 @@ func TestAppendAny(t *testing.T) { assert.Eq(t, []byte("1"), 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) +}