/ console / program / src / data / identifier / to_field.rs
to_field.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the alphavm 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  
16  use super::*;
17  
18  impl<N: Network> ToField for Identifier<N> {
19      type Field = Field<N>;
20  
21      /// Returns the identifier as a field element.
22      fn to_field(&self) -> Result<Self::Field> {
23          (&self).to_field()
24      }
25  }
26  
27  impl<N: Network> ToField for &Identifier<N> {
28      type Field = Field<N>;
29  
30      /// Returns the identifier as a field element.
31      fn to_field(&self) -> Result<Self::Field> {
32          Ok(self.0)
33      }
34  }
35  
36  #[cfg(test)]
37  mod tests {
38      use super::*;
39      use crate::data::identifier::tests::sample_identifier_as_string;
40      use alphavm_console_network::MainnetV0;
41  
42      type CurrentNetwork = MainnetV0;
43  
44      const ITERATIONS: usize = 100;
45  
46      #[test]
47      fn test_to_field() -> Result<()> {
48          let mut rng = TestRng::default();
49  
50          for _ in 0..ITERATIONS {
51              // Sample a random fixed-length alphanumeric string, that always starts with an alphabetic character.
52              let expected_string = sample_identifier_as_string::<CurrentNetwork>(&mut rng)?;
53              // Recover the field element from the bits.
54              let expected_field = Field::<CurrentNetwork>::from_bits_le(&expected_string.to_bits_le())?;
55  
56              let candidate = Identifier::<CurrentNetwork>::from_str(&expected_string)?;
57              assert_eq!(expected_field, candidate.to_field()?);
58          }
59          Ok(())
60      }
61  }