From ec7323159c129ac0d5ed3b7a28010077544038fd Mon Sep 17 00:00:00 2001 From: Sean Bowe Date: Mon, 19 Feb 2018 19:27:03 -0700 Subject: [PATCH] Booleanize u64 objects. --- src/circuit/boolean.rs | 54 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/src/circuit/boolean.rs b/src/circuit/boolean.rs index c6cb088..23ec447 100644 --- a/src/circuit/boolean.rs +++ b/src/circuit/boolean.rs @@ -234,6 +234,36 @@ impl AllocatedBit { } } +pub fn u64_into_allocated_bits_be>( + mut cs: CS, + value: Option +) -> Result, SynthesisError> +{ + let values = match value { + Some(ref value) => { + let mut tmp = Vec::with_capacity(64); + + for i in (0..64).rev() { + tmp.push(Some(*value >> i & 1 == 1)); + } + + tmp + }, + None => { + vec![None; 64] + } + }; + + let bits = values.into_iter().enumerate().map(|(i, b)| { + AllocatedBit::alloc( + cs.namespace(|| format!("bit {}", i)), + b + ) + }).collect::, SynthesisError>>()?; + + Ok(bits) +} + pub fn field_into_allocated_bits_be, F: PrimeField>( mut cs: CS, value: Option @@ -553,7 +583,8 @@ mod test { use super::{ AllocatedBit, Boolean, - field_into_allocated_bits_be + field_into_allocated_bits_be, + u64_into_allocated_bits_be }; #[test] @@ -1175,6 +1206,27 @@ mod test { } } + #[test] + fn test_u64_into_allocated_bits_be() { + let mut cs = TestConstraintSystem::::new(); + + let bits = u64_into_allocated_bits_be(&mut cs, Some(17234652694787248421)).unwrap(); + + assert!(cs.is_satisfied()); + + assert_eq!(bits.len(), 64); + + assert_eq!(bits[0].value.unwrap(), true); + assert_eq!(bits[1].value.unwrap(), true); + assert_eq!(bits[2].value.unwrap(), true); + assert_eq!(bits[3].value.unwrap(), false); + assert_eq!(bits[4].value.unwrap(), true); + assert_eq!(bits[5].value.unwrap(), true); + assert_eq!(bits[20].value.unwrap(), true); + assert_eq!(bits[21].value.unwrap(), false); + assert_eq!(bits[22].value.unwrap(), false); + } + #[test] fn test_field_into_allocated_bits_be() { let mut cs = TestConstraintSystem::::new();