/ console / types / group / src / bytes.rs
bytes.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the deltavm 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<E: Environment> FromBytes for Group<E> {
19      /// Reads the group from a buffer.
20      #[inline]
21      fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22          Self::from_x_coordinate(FromBytes::read_le(&mut reader)?).map_err(into_io_error)
23      }
24  }
25  
26  impl<E: Environment> ToBytes for Group<E> {
27      /// Writes the group to a buffer.
28      #[inline]
29      fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
30          self.to_x_coordinate().write_le(&mut writer)
31      }
32  }
33  
34  #[cfg(test)]
35  mod tests {
36      use super::*;
37      use deltavm_console_network_environment::Console;
38  
39      type CurrentEnvironment = Console;
40  
41      const ITERATIONS: u64 = 10_000;
42  
43      #[test]
44      fn test_bytes() -> Result<()> {
45          let mut rng = TestRng::default();
46  
47          for _ in 0..ITERATIONS {
48              // Sample a new group.
49              let expected = Group::<CurrentEnvironment>::new(Uniform::rand(&mut rng));
50  
51              // Check the byte representation.
52              let expected_bytes = expected.to_bytes_le()?;
53              assert_eq!(expected, Group::read_le(&expected_bytes[..])?);
54              assert_eq!(expected, Group::read_le_unchecked(&expected_bytes[..])?);
55              assert!(Group::<CurrentEnvironment>::read_le(&expected_bytes[1..]).is_err());
56              assert!(Group::<CurrentEnvironment>::read_le_unchecked(&expected_bytes[1..]).is_err());
57          }
58          Ok(())
59      }
60  }