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:
parent
83d4e5e860
commit
613c5f8ff0
@ -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
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user