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)).
This commit is contained in:
xfy 2026-06-04 10:48:51 +08:00
parent 83d4e5e860
commit 613c5f8ff0

View File

@ -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
}