Debian Codegraph @

utils/xor/xor_generic.go

raw symbols SCIP
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Modifications copyright 2022 The Pion Authors, governed by
6 // the MIT license.
7
8 //go:build !amd64 && !ppc64 && !ppc64le && !arm64 && !arm
9
10 // Package xor provides utility functions used by other Pion
11 // packages. Generic arch.
12 package xor
13
14 import (
15 "runtime"
16 "unsafe"
17 )
18
19 const wordSize = int(unsafe.Sizeof(uintptr(0))) // nolint:gosec
20 const supportsUnaligned = runtime.GOARCH == "386" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "s390x" // nolint:gochecknoglobals
21
22 func isAligned(a *byte) bool {
23 return uintptr(unsafe.Pointer(a))%uintptr(wordSize) == 0
24 }
25
26 // XorBytes xors the bytes in a and b. The destination should have enough
27 // space, otherwise xorBytes will panic. Returns the number of bytes xor'd.
28 //revive:disable-next-line
29 func XorBytes(dst, a, b []byte) int {
30 n := len(a)
31 if len(b) < n {
32 n = len(b)
33 }
34 if n == 0 {
35 return 0
36 }
37
38 switch {
39 case supportsUnaligned:
40 fastXORBytes(dst, a, b, n)
41 case isAligned(&dst[0]) && isAligned(&a[0]) && isAligned(&b[0]):
42 fastXORBytes(dst, a, b, n)
43 default:
44 safeXORBytes(dst, a, b, n)
45 }
46 return n
47 }
48
49 // fastXORBytes xors in bulk. It only works on architectures that
50 // support unaligned read/writes.
51 // n needs to be smaller or equal than the length of a and b.
52 func fastXORBytes(dst, a, b []byte, n int) {
53 // Assert dst has enough space
54 _ = dst[n-1]
55
56 w := n / wordSize
57 if w > 0 {
58 dw := *(*[]uintptr)(unsafe.Pointer(&dst)) // nolint:gosec
59 aw := *(*[]uintptr)(unsafe.Pointer(&a)) // nolint:gosec
60 bw := *(*[]uintptr)(unsafe.Pointer(&b)) // nolint:gosec
61 for i := 0; i < w; i++ {
62 dw[i] = aw[i] ^ bw[i]
63 }
64 }
65
66 for i := (n - n%wordSize); i < n; i++ {
67 dst[i] = a[i] ^ b[i]
68 }
69 }
70
71 // n needs to be smaller or equal than the length of a and b.
72 func safeXORBytes(dst, a, b []byte, n int) {
73 for i := 0; i < n; i++ {
74 dst[i] = a[i] ^ b[i]
75 }
76 }