-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathxor_unaligned.go
62 lines (53 loc) · 1.27 KB
/
xor_unaligned.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// +build 386 amd64,!go1.7 ppc64 ppc64le s390x
package fastxor
import (
"unsafe"
)
const wordSize = int(unsafe.Sizeof(uintptr(0)))
// Bytes stores (a xor b) in dst, stopping when the end of any slice is
// reached. It returns the number of bytes xor'd.
func Bytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
if n == 0 {
return 0
}
// Assert dst has enough space
_ = dst[n-1]
w := n / wordSize
if w > 0 {
dw := *(*[]uintptr)(unsafe.Pointer(&dst))
aw := *(*[]uintptr)(unsafe.Pointer(&a))
bw := *(*[]uintptr)(unsafe.Pointer(&b))
for i := 0; i < w; i++ {
dw[i] = aw[i] ^ bw[i]
}
}
for i := (n - n%wordSize); i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
// Byte xors each byte in a with b and stores the result in dst, stopping when
// the end of either dst or a is reached. It returns the number of bytes
// xor'd.
func Byte(dst, a []byte, b byte) int {
n := len(a)
if len(dst) < n {
n = len(dst)
}
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b
}
return n
}
// Block stores (a xor b) in dst, where a, b, and dst all have length 16.
func Block(dst, a, b []byte) {
dw := *(*[]uintptr)(unsafe.Pointer(&dst))
aw := *(*[]uintptr)(unsafe.Pointer(&a))
bw := *(*[]uintptr)(unsafe.Pointer(&b))
dw[0] = aw[0] ^ bw[0]
dw[1] = aw[1] ^ bw[1]
}