snarkvm_circuit_program/data/identifier/
from_bits.rs1use super::*;
17
18impl<A: Aleo> FromBits for Identifier<A> {
19 type Boolean = Boolean<A>;
20
21 fn from_bits_le(bits_le: &[Self::Boolean]) -> Self {
23 debug_assert!(bits_le.len() <= A::BaseField::size_in_bits(), "Identifier exceeds the maximum bits allowed");
27
28 let field = Field::from_bits_le(bits_le);
30
31 let num_bytes = match console::Identifier::<A::Network>::from_bits_le(&bits_le.eject_value()) {
33 Ok(console_identifier) => console_identifier.size_in_bits() / 8,
34 Err(error) => A::halt(format!("Failed to recover an identifier from bits: {error}")),
35 };
36
37 let max_bytes = A::BaseField::size_in_data_bits() / 8; match num_bytes as usize <= max_bytes {
40 true => Self(field, num_bytes),
42 false => A::halt("Identifier exceeds the maximum capacity allowed"),
43 }
44 }
45
46 fn from_bits_be(bits_be: &[Self::Boolean]) -> Self {
48 Self::from_bits_le(bits_be.iter().rev().cloned().collect::<Vec<_>>().as_slice())
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55 use crate::{Circuit, data::identifier::tests::sample_console_identifier};
56
57 use anyhow::Result;
58
59 const ITERATIONS: u64 = 100;
60
61 fn check_from_bits_le(num_constants: u64, num_public: u64, num_private: u64, num_constraints: u64) -> Result<()> {
62 for _ in 0..ITERATIONS {
63 let console_identifier = sample_console_identifier::<Circuit>()?;
65 let circuit_bits: Vec<_> = Inject::constant(console_identifier.to_bits_le());
67
68 Circuit::scope("Identifier FromBits", || {
69 let candidate = Identifier::<Circuit>::from_bits_le(&circuit_bits);
70 assert_eq!(Mode::Constant, candidate.eject_mode());
71 assert_eq!(console_identifier, candidate.eject_value());
72 assert_scope!(num_constants, num_public, num_private, num_constraints);
73 });
74 Circuit::reset();
75 }
76 Ok(())
77 }
78
79 fn check_from_bits_be(num_constants: u64, num_public: u64, num_private: u64, num_constraints: u64) -> Result<()> {
80 for _ in 0..ITERATIONS {
81 let console_identifier = sample_console_identifier::<Circuit>()?;
83 let circuit_bits: Vec<_> = Inject::constant(console_identifier.to_bits_be());
85
86 Circuit::scope("Identifier FromBits", || {
87 let candidate = Identifier::<Circuit>::from_bits_be(&circuit_bits);
88 assert_eq!(Mode::Constant, candidate.eject_mode());
89 assert_eq!(console_identifier, candidate.eject_value());
90 assert_scope!(num_constants, num_public, num_private, num_constraints);
91 });
92 Circuit::reset();
93 }
94 Ok(())
95 }
96
97 #[test]
98 fn test_from_bits_le() -> Result<()> {
99 check_from_bits_le(0, 0, 0, 0)
100 }
101
102 #[test]
103 fn test_from_bits_be() -> Result<()> {
104 check_from_bits_be(0, 0, 0, 0)
105 }
106}