From efd7660f41ddf3474fccee26d56d8e1458f423cf Mon Sep 17 00:00:00 2001 From: Tom French <15848336+TomAFrench@users.noreply.github.com> Date: Fri, 12 Jan 2024 16:52:39 +0000 Subject: [PATCH] feat: replace bitwise ORs in `U256:from_bytes32` with addition (#3947) Addition and OR are the same here due to the lack of overlaps in the bit representations of the bytes making up each u64. It's then more efficient to just add them together. --- .../src/crates/types/src/utils/uint256.nr | 57 ++++++++++--------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/yarn-project/noir-protocol-circuits/src/crates/types/src/utils/uint256.nr b/yarn-project/noir-protocol-circuits/src/crates/types/src/utils/uint256.nr index 82d581796bf..7731218c9eb 100644 --- a/yarn-project/noir-protocol-circuits/src/crates/types/src/utils/uint256.nr +++ b/yarn-project/noir-protocol-circuits/src/crates/types/src/utils/uint256.nr @@ -14,41 +14,42 @@ struct U256 { impl U256 { pub fn from_bytes32(bytes : [u8;32]) -> U256 { + // We use addition rather than a bitwise OR as the bitshifts ensure that none of the bytes overlap each other. let high_0 = ((bytes[0] as u64) << 56) - | ((bytes[1] as u64) << 48) - | ((bytes[2] as u64) << 40) - | ((bytes[3] as u64) << 32) - | ((bytes[4] as u64) << 24) - | ((bytes[5] as u64) << 16) - | ((bytes[6] as u64) << 8) - | (bytes[7] as u64); + + ((bytes[1] as u64) << 48) + + ((bytes[2] as u64) << 40) + + ((bytes[3] as u64) << 32) + + ((bytes[4] as u64) << 24) + + ((bytes[5] as u64) << 16) + + ((bytes[6] as u64) << 8) + + (bytes[7] as u64); let high_1 = ((bytes[8] as u64) << 56) - | ((bytes[9] as u64) << 48) - | ((bytes[10] as u64) << 40) - | ((bytes[11] as u64) << 32) - | ((bytes[12] as u64) << 24) - | ((bytes[13] as u64) << 16) - | ((bytes[14] as u64) << 8) - | (bytes[15] as u64); + + ((bytes[9] as u64) << 48) + + ((bytes[10] as u64) << 40) + + ((bytes[11] as u64) << 32) + + ((bytes[12] as u64) << 24) + + ((bytes[13] as u64) << 16) + + ((bytes[14] as u64) << 8) + + (bytes[15] as u64); let low_0 = ((bytes[16] as u64) << 56) - | ((bytes[17] as u64) << 48) - | ((bytes[18] as u64) << 40) - | ((bytes[19] as u64) << 32) - | ((bytes[20] as u64) << 24) - | ((bytes[21] as u64) << 16) - | ((bytes[22] as u64) << 8) - | (bytes[23] as u64); + + ((bytes[17] as u64) << 48) + + ((bytes[18] as u64) << 40) + + ((bytes[19] as u64) << 32) + + ((bytes[20] as u64) << 24) + + ((bytes[21] as u64) << 16) + + ((bytes[22] as u64) << 8) + + (bytes[23] as u64); let low_1 = ((bytes[24] as u64) << 56) - | ((bytes[25] as u64) << 48) - | ((bytes[26] as u64) << 40) - | ((bytes[27] as u64) << 32) - | ((bytes[28] as u64) << 24) - | ((bytes[29] as u64) << 16) - | ((bytes[30] as u64) << 8) - | (bytes[31] as u64); + + ((bytes[25] as u64) << 48) + + ((bytes[26] as u64) << 40) + + ((bytes[27] as u64) << 32) + + ((bytes[28] as u64) << 24) + + ((bytes[29] as u64) << 16) + + ((bytes[30] as u64) << 8) + + (bytes[31] as u64); U256{inner : [high_0, high_1, low_0, low_1]} }