Debian Codegraph @

mem/index_pair.go

raw
1 package mem
2
3 import (
4 "bytes"
5 )
6
7 // IndexPair returns the byte index of the first pair of two equal elements of
8 // size n.
9 //
10 // If no pairs of equal elements were found, -1 is returned.
11 func IndexPair(b []byte, n int) int {
12 if len(b)%n != 0 {
13 panic("input length is not a multiple of the item size")
14 }
15 // Delegate to indexPair to keep the function cost low and allow the size
16 // check to be inlined and the modulo optimized away for power of two sizes
17 // known at compile time.
18 return indexPair(b, n)
19 }
20
21 func indexPair(b []byte, n int) int {
22 switch n {
23 case 1:
24 return indexPair1(b)
25 case 2:
26 return indexPair2(b)
27 case 4:
28 return indexPair4(b)
29 case 8:
30 return indexPair8(b)
31 case 16:
32 return indexPair16(b)
33 case 32:
34 return indexPair32(b)
35 default:
36 return indexPairGeneric(b, n)
37 }
38 }
39
40 func indexPairGeneric(b []byte, n int) int {
41 for i := n; i < len(b); i += n {
42 if bytes.Equal(b[i-n:i], b[i:i+n]) {
43 return i - n
44 }
45 }
46 return -1
47 }