From 613c5f8ff00f8afdea75293e3137495d19ccda21 Mon Sep 17 00:00:00 2001 From: xfy Date: Thu, 4 Jun 2026 10:48:51 +0800 Subject: [PATCH] perf(utils): add BytesContainsFold for zero-allocation case-insensitive search Reports whether a byte slice contains a subslice, case-insensitively, without allocating (unlike bytes.Contains(bytes.ToLower(b), sub)). --- internal/utils/bytes.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/internal/utils/bytes.go b/internal/utils/bytes.go index bc890a8..4ca1650 100644 --- a/internal/utils/bytes.go +++ b/internal/utils/bytes.go @@ -5,7 +5,10 @@ // 作者:xfy package utils -import "unsafe" +import ( + "bytes" + "unsafe" +) // B2s converts byte slice to string without allocation. // WARNING: The returned string shares memory with the original slice. @@ -26,3 +29,19 @@ func S2b(s string) []byte { } return unsafe.Slice(unsafe.StringData(s), len(s)) } + +func BytesContainsFold(b, sub []byte) bool { + if len(sub) == 0 { + return true + } + if len(sub) > len(b) { + return false + } + end := len(b) - len(sub) + 1 + for i := 0; i < end; i++ { + if bytes.EqualFold(b[i:i+len(sub)], sub) { + return true + } + } + return false +}