/ console / program / src / data / identifier / size_in_bits.rs
size_in_bits.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> Identifier<N> {
19      /// Returns the number of bits of this identifier.
20      pub fn size_in_bits(&self) -> u8 {
21          // The size in bits always fits in a u8, as the underlying representation is a field element.
22          debug_assert!(Field::<N>::size_in_data_bits() <= u8::MAX as usize);
23          // Convert the size to bits (as a byte-aligned multiple).
24          8 * self.1
25      }
26  }
27  
28  #[cfg(test)]
29  mod tests {
30      use super::*;
31      use crate::data::identifier::tests::sample_identifier_as_string;
32      use alphavm_console_network::MainnetV0;
33  
34      type CurrentNetwork = MainnetV0;
35  
36      const ITERATIONS: usize = 100;
37  
38      #[test]
39      fn test_size_in_bits() -> Result<()> {
40          let mut rng = TestRng::default();
41  
42          for _ in 0..ITERATIONS {
43              // Sample a random fixed-length alphanumeric string, that always starts with an alphabetic character.
44              let expected_string = sample_identifier_as_string::<CurrentNetwork>(&mut rng)?;
45  
46              let candidate = Identifier::<CurrentNetwork>::from_str(&expected_string)?;
47              assert_eq!(expected_string.len() * 8, candidate.size_in_bits() as usize);
48          }
49          Ok(())
50      }
51  }