| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package xor |
| 8 |
|
| 9 |
import ( |
| 10 |
"golang.org/x/sys/cpu" |
| 11 |
"unsafe" |
| 12 |
) |
| 13 |
|
| 14 |
const wordSize = int(unsafe.Sizeof(uintptr(0))) |
| 15 |
var hasNEON = cpu.ARM.HasNEON |
| 16 |
|
| 17 |
func isAligned(a *byte) bool { |
| 18 |
return uintptr(unsafe.Pointer(a))%uintptr(wordSize) == 0 |
| 19 |
} |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
func XorBytes(dst, a, b []byte) int { |
| 25 |
n := len(a) |
| 26 |
if len(b) < n { |
| 27 |
n = len(b) |
| 28 |
} |
| 29 |
if n == 0 { |
| 30 |
return 0 |
| 31 |
} |
| 32 |
|
| 33 |
_ = dst[n-1] |
| 34 |
|
| 35 |
if hasNEON { |
| 36 |
xorBytesNEON32(&dst[0], &a[0], &b[0], n) |
| 37 |
} else if isAligned(&dst[0]) && isAligned(&a[0]) && isAligned(&b[0]) { |
| 38 |
xorBytesARM32(&dst[0], &a[0], &b[0], n) |
| 39 |
} else { |
| 40 |
safeXORBytes(dst, a, b, n) |
| 41 |
} |
| 42 |
return n |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
func safeXORBytes(dst, a, b []byte, n int) { |
| 47 |
for i := 0; i < n; i++ { |
| 48 |
dst[i] = a[i] ^ b[i] |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
func xorBytesARM32(dst, a, b *byte, n int) |
| 54 |
|
| 55 |
|
| 56 |
func xorBytesNEON32(dst, a, b *byte, n int) |