github.com/iDigitalFlame/xmt@v0.5.4/data/crypto/subtle/c_xor.go (about)

     1  //go:build !go1.20
     2  // +build !go1.20
     3  
     4  // Copyright (C) 2020 - 2023 iDigitalFlame
     5  //
     6  // This program is free software: you can redistribute it and/or modify
     7  // it under the terms of the GNU General Public License as published by
     8  // the Free Software Foundation, either version 3 of the License, or
     9  // any later version.
    10  //
    11  // This program is distributed in the hope that it will be useful,
    12  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  // GNU General Public License for more details.
    15  //
    16  // You should have received a copy of the GNU General Public License
    17  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    18  //
    19  
    20  // Package subtle is similar to the 'cipher/subtle', only needed for very specific
    21  // crypto operations.
    22  package subtle
    23  
    24  import (
    25  	// Importing unsafe to link "xorBytes"
    26  	_ "unsafe"
    27  	// Importing crypto/cipher" to link "xorBytes"
    28  	_ "crypto/cipher"
    29  )
    30  
    31  // XorOp will call the 'XorBytes' function but write the value back to the value
    32  // instead. This one assumes that the key value is less than or equal to the
    33  // value.
    34  //
    35  // If you need finer control, use the 'XorBytes' function.
    36  func XorOp(value, key []byte) {
    37  	if len(key) == 0 || len(value) == 0 {
    38  		return
    39  	}
    40  	if len(key) == len(value) {
    41  		xorBytes(value, key, value)
    42  		return
    43  	}
    44  	for n := 0; n < len(value); {
    45  		n += xorBytes(value[n:], key, value[n:])
    46  	}
    47  }
    48  
    49  //go:linkname xorBytes crypto/cipher.xorBytes
    50  func xorBytes(dst, a, b []byte) int
    51  
    52  // XorBytes is the runtime import from "crypto/cipher.xorBytes" that can use
    53  // hardware instructions for a 200% faster XOR operation.
    54  //
    55  // This variant will overlap the xor for the entire backing array, depending
    56  // on which one is larger.
    57  func XorBytes(dst, a, b []byte) int {
    58  	var n int
    59  	if len(a) < len(b) {
    60  		for n < len(b) {
    61  			n += xorBytes(dst[n:], a, b[n:])
    62  		}
    63  		return n
    64  	}
    65  	for n < len(a) {
    66  		n += xorBytes(dst[n:], b, a[n:])
    67  	}
    68  	return n
    69  }