Skip to content

Commit 8b43d18

Browse files
authored
Merge pull request ProvableHQ#2279 from bishopcheckmate/perf/console-from-bits
perf: optimize console field and scalar from_bits_le
2 parents 5ad8742 + 68cb0bf commit 8b43d18

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

console/types/field/src/from_bits.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,14 @@ impl<E: Environment> FromBits for Field<E> {
4545
// Return the field.
4646
Ok(Field { field: E::Field::from_bigint(field).ok_or_else(|| anyhow!("Invalid field from bits"))? })
4747
} else {
48-
// Construct the sanitized list of bits, resizing up if necessary.
49-
let mut bits_le = bits_le.iter().take(size_in_bits).cloned().collect::<Vec<_>>();
50-
bits_le.resize(size_in_bits, false);
48+
// Construct the sanitized list of bits padded with `false`
49+
let mut sanitized_bits = vec![false; size_in_bits];
50+
// Note: This is safe, because we just checked that the length of bits isn't bigger
51+
// than `size_in_data_bits` which is equal to `size_in_bits - 1`.
52+
sanitized_bits[..num_bits].copy_from_slice(bits_le);
5153

5254
// Recover the native field.
53-
let field = E::Field::from_bigint(E::BigInteger::from_bits_le(&bits_le)?)
55+
let field = E::Field::from_bigint(E::BigInteger::from_bits_le(&sanitized_bits)?)
5456
.ok_or_else(|| anyhow!("Invalid field from bits"))?;
5557

5658
// Return the field.

console/types/scalar/src/from_bits.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,14 @@ impl<E: Environment> FromBits for Scalar<E> {
4848
// Return the scalar.
4949
Ok(Scalar { scalar: E::Scalar::from_bigint(scalar).ok_or_else(|| anyhow!("Invalid scalar from bits"))? })
5050
} else {
51-
// Construct the sanitized list of bits, resizing up if necessary.
52-
let mut bits_le = bits_le.iter().take(size_in_bits).cloned().collect::<Vec<_>>();
53-
bits_le.resize(size_in_bits, false);
51+
// Construct the sanitized list of bits padded with `false`
52+
let mut sanitized_bits = vec![false; size_in_bits];
53+
// Note: This is safe, because we just checked that the length of bits isn't bigger
54+
// than `size_in_data_bits` which is equal to `size_in_bits - 1`.
55+
sanitized_bits[..num_bits].copy_from_slice(bits_le);
5456

5557
// Recover the native scalar.
56-
let scalar = E::Scalar::from_bigint(E::BigInteger::from_bits_le(&bits_le)?)
58+
let scalar = E::Scalar::from_bigint(E::BigInteger::from_bits_le(&sanitized_bits)?)
5759
.ok_or_else(|| anyhow!("Invalid scalar from bits"))?;
5860

5961
// Return the scalar.

0 commit comments

Comments
 (0)