Skip to content

Commit

Permalink
Merge pull request #2279 from bishopcheckmate/perf/console-from-bits
Browse files Browse the repository at this point in the history
perf: optimize console field and scalar from_bits_le
  • Loading branch information
howardwu authored Jan 9, 2024
2 parents 5ad8742 + 68cb0bf commit 8b43d18
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
10 changes: 6 additions & 4 deletions console/types/field/src/from_bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,14 @@ impl<E: Environment> FromBits for Field<E> {
// Return the field.
Ok(Field { field: E::Field::from_bigint(field).ok_or_else(|| anyhow!("Invalid field from bits"))? })
} else {
// Construct the sanitized list of bits, resizing up if necessary.
let mut bits_le = bits_le.iter().take(size_in_bits).cloned().collect::<Vec<_>>();
bits_le.resize(size_in_bits, false);
// Construct the sanitized list of bits padded with `false`
let mut sanitized_bits = vec![false; size_in_bits];
// Note: This is safe, because we just checked that the length of bits isn't bigger
// than `size_in_data_bits` which is equal to `size_in_bits - 1`.
sanitized_bits[..num_bits].copy_from_slice(bits_le);

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

// Return the field.
Expand Down
10 changes: 6 additions & 4 deletions console/types/scalar/src/from_bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,14 @@ impl<E: Environment> FromBits for Scalar<E> {
// Return the scalar.
Ok(Scalar { scalar: E::Scalar::from_bigint(scalar).ok_or_else(|| anyhow!("Invalid scalar from bits"))? })
} else {
// Construct the sanitized list of bits, resizing up if necessary.
let mut bits_le = bits_le.iter().take(size_in_bits).cloned().collect::<Vec<_>>();
bits_le.resize(size_in_bits, false);
// Construct the sanitized list of bits padded with `false`
let mut sanitized_bits = vec![false; size_in_bits];
// Note: This is safe, because we just checked that the length of bits isn't bigger
// than `size_in_data_bits` which is equal to `size_in_bits - 1`.
sanitized_bits[..num_bits].copy_from_slice(bits_le);

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

// Return the scalar.
Expand Down

0 comments on commit 8b43d18

Please sign in to comment.