perf: reduce allocations in Boolean's SignExtend impl

Signed-off-by: ljedrz <ljedrz@gmail.com>
This commit is contained in:
ljedrz 2020-10-22 16:28:02 +02:00
parent 78f98f1f26
commit 710bbc6730

View File

@ -16,6 +16,8 @@
use snarkos_models::gadgets::utilities::boolean::Boolean; use snarkos_models::gadgets::utilities::boolean::Boolean;
use std::iter;
/// Sign extends an array of bits to the desired length. /// Sign extends an array of bits to the desired length.
/// Expects least significant bit first /// Expects least significant bit first
pub trait SignExtend pub trait SignExtend
@ -30,10 +32,10 @@ impl SignExtend for Boolean {
fn sign_extend(bits: &[Boolean], length: usize) -> Vec<Boolean> { fn sign_extend(bits: &[Boolean], length: usize) -> Vec<Boolean> {
let msb = bits.last().expect("empty bit list"); let msb = bits.last().expect("empty bit list");
let bits_needed = length - bits.len(); let bits_needed = length - bits.len();
let mut extension = vec![*msb; bits_needed];
let mut result = Vec::from(bits); let mut result = Vec::with_capacity(length);
result.append(&mut extension); result.extend_from_slice(bits);
result.extend(iter::repeat(*msb).take(bits_needed));
result result
} }