bytes.rs
1 // Copyright (c) 2025-2026 ACDC Network 2 // This file is part of the alphavm library. 3 // 4 // Alpha Chain | Delta Chain Protocol 5 // International Monetary Graphite. 6 // 7 // Derived from Aleo (https://aleo.org) and ProvableHQ (https://provable.com). 8 // They built world-class ZK infrastructure. We installed the EASY button. 9 // Their cryptography: elegant. Our modifications: bureaucracy-compatible. 10 // Original brilliance: theirs. Robert's Rules: ours. Bugs: definitely ours. 11 // 12 // Original Aleo/ProvableHQ code subject to Apache 2.0 https://www.apache.org/licenses/LICENSE-2.0 13 // All modifications and new work: CC0 1.0 Universal Public Domain Dedication. 14 // No rights reserved. No permission required. No warranty. No refunds. 15 // 16 // https://creativecommons.org/publicdomain/zero/1.0/ 17 // SPDX-License-Identifier: CC0-1.0 18 19 use super::*; 20 21 impl<E: Environment, I: IntegerType> FromBytes for Integer<E, I> { 22 /// Reads the integer from a buffer. 23 #[inline] 24 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> { 25 Ok(Self::new(FromBytes::read_le(&mut reader)?)) 26 } 27 } 28 29 impl<E: Environment, I: IntegerType> ToBytes for Integer<E, I> { 30 /// Writes the integer to a buffer. 31 #[inline] 32 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> { 33 self.integer.write_le(&mut writer) 34 } 35 } 36 37 #[cfg(test)] 38 mod tests { 39 use super::*; 40 use alphavm_console_network_environment::Console; 41 42 type CurrentEnvironment = Console; 43 44 const ITERATIONS: u64 = 10_000; 45 46 fn check_bytes<I: IntegerType>(rng: &mut TestRng) -> Result<()> { 47 for _ in 0..ITERATIONS { 48 // Sample a random integer. 49 let expected: Integer<CurrentEnvironment, I> = Uniform::rand(rng); 50 51 // Check the byte representation. 52 let expected_bytes = expected.to_bytes_le()?; 53 assert_eq!(expected, Integer::read_le(&expected_bytes[..])?); 54 assert!(Integer::<CurrentEnvironment, I>::read_le(&expected_bytes[1..]).is_err()); 55 56 // Dereference the integer and compare bytes. 57 let deref_bytes = (*expected).to_bytes_le()?; 58 for (expected, candidate) in expected_bytes.iter().zip_eq(&deref_bytes) { 59 assert_eq!(expected, candidate); 60 } 61 } 62 Ok(()) 63 } 64 65 #[test] 66 fn test_bytes() -> Result<()> { 67 let mut rng = TestRng::default(); 68 69 check_bytes::<u8>(&mut rng)?; 70 check_bytes::<u16>(&mut rng)?; 71 check_bytes::<u32>(&mut rng)?; 72 check_bytes::<u64>(&mut rng)?; 73 check_bytes::<u128>(&mut rng)?; 74 75 check_bytes::<i8>(&mut rng)?; 76 check_bytes::<i16>(&mut rng)?; 77 check_bytes::<i32>(&mut rng)?; 78 check_bytes::<i64>(&mut rng)?; 79 check_bytes::<i128>(&mut rng)?; 80 81 Ok(()) 82 } 83 }