diff --git a/ahocorasick.go b/ahocorasick.go index 0ec4628..5823866 100644 --- a/ahocorasick.go +++ b/ahocorasick.go @@ -116,7 +116,7 @@ func (ac AhoCorasick) PatternCount() int { // Iter gives an iterator over the built patterns func (ac AhoCorasick) Iter(haystack string) Iter { - return ac.IterByte([]byte(haystack)) + return ac.IterByte(unsafeBytes(haystack)) } // IterByte gives an iterator over the built patterns @@ -140,7 +140,7 @@ func (ac AhoCorasick) IterByte(haystack []byte) Iter { // Iter gives an iterator over the built patterns with overlapping matches func (ac AhoCorasick) IterOverlapping(haystack string) Iter { - return ac.IterOverlappingByte([]byte(haystack)) + return ac.IterOverlappingByte(unsafeBytes(haystack)) } // IterOverlappingByte gives an iterator over the built patterns with overlapping matches @@ -293,7 +293,7 @@ func NewAhoCorasickBuilder(o Opts) AhoCorasickBuilder { func (a *AhoCorasickBuilder) Build(patterns []string) AhoCorasick { bytePatterns := make([][]byte, len(patterns)) for pati, pat := range patterns { - bytePatterns[pati] = []byte(pat) + bytePatterns[pati] = unsafeBytes(pat) } return a.BuildByte(bytePatterns) diff --git a/unsafe.go b/unsafe.go new file mode 100644 index 0000000..39bace8 --- /dev/null +++ b/unsafe.go @@ -0,0 +1,12 @@ +package aho_corasick + +import ( + "reflect" + "unsafe" +) + +func unsafeBytes(s string) []byte { + str := (*reflect.StringHeader)(unsafe.Pointer(&s)) + slice := reflect.SliceHeader{Data: str.Data, Len: str.Len, Cap: str.Len} + return *(*[]byte)(unsafe.Pointer(&slice)) +}