| 1 |
package mem |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
) |
| 6 |
|
| 7 |
// CountPair 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, len(b) is returned. |
| 11 |
func CountPair(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 countPair 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 countPair(b, n) |
| 19 |
} |
| 20 |
|
| 21 |
func countPair(b []byte, n int) int { |
| 22 |
switch n { |
| 23 |
case 1: |
| 24 |
return countPair1(b) |
| 25 |
case 2: |
| 26 |
return countPair2(b) |
| 27 |
case 4: |
| 28 |
return countPair4(b) |
| 29 |
case 8: |
| 30 |
return countPair8(b) |
| 31 |
case 16: |
| 32 |
return countPair16(b) |
| 33 |
case 32: |
| 34 |
return countPair32(b) |
| 35 |
default: |
| 36 |
return countPairGeneric(b, n) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
func countPairGeneric(b []byte, n int) int { |
| 41 |
c := 0 |
| 42 |
for i := n; i < len(b); i += n { |
| 43 |
if bytes.Equal(b[i-n:i], b[i:i+n]) { |
| 44 |
c++ |
| 45 |
} |
| 46 |
} |
| 47 |
return c |
| 48 |
} |