snarkvm_console_program/data/identifier/
from_field.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> FromField for Identifier<N> {
19    type Field = Field<N>;
20
21    /// Initializes a new identifier from a field element.
22    fn from_field(field: &Self::Field) -> Result<Self> {
23        // Convert the field to a list of little-endian bits.
24        Self::from_bits_le(&field.to_bits_le())
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use crate::data::identifier::tests::sample_identifier;
32    use snarkvm_console_network::MainnetV0;
33
34    type CurrentNetwork = MainnetV0;
35
36    const ITERATIONS: usize = 100;
37
38    #[test]
39    fn test_from_field() -> Result<()> {
40        let mut rng = TestRng::default();
41
42        for _ in 0..ITERATIONS {
43            // Sample a random fixed-length alphanumeric identifier, that always starts with an alphabetic character.
44            let identifier = sample_identifier::<CurrentNetwork>(&mut rng)?;
45            assert_eq!(identifier, Identifier::from_field(&identifier.to_field()?)?);
46        }
47        Ok(())
48    }
49}