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<N: Network> FromBytes for Solution<N> { 19 /// Reads the solution from the buffer. 20 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> { 21 let partial_solution = PartialSolution::read_le(&mut reader)?; 22 let target = u64::read_le(&mut reader)?; 23 24 Ok(Self::new(partial_solution, target)) 25 } 26 } 27 28 impl<N: Network> ToBytes for Solution<N> { 29 /// Writes the solution to the buffer. 30 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> { 31 self.partial_solution.write_le(&mut writer)?; 32 self.target.write_le(&mut writer) 33 } 34 } 35 36 #[cfg(test)] 37 mod tests { 38 use super::*; 39 use console::{account::PrivateKey, network::MainnetV0}; 40 41 type CurrentNetwork = MainnetV0; 42 43 #[test] 44 fn test_bytes() -> Result<()> { 45 let mut rng = TestRng::default(); 46 let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?; 47 let address = Address::try_from(private_key)?; 48 49 // Sample a new solution. 50 let partial_solution = PartialSolution::new(rng.r#gen(), address, u64::rand(&mut rng)).unwrap(); 51 let target = u64::rand(&mut rng); 52 let expected = Solution::new(partial_solution, target); 53 54 // Check the byte representation. 55 let expected_bytes = expected.to_bytes_le()?; 56 assert_eq!(expected, Solution::read_le(&expected_bytes[..])?); 57 assert!(Solution::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err()); 58 59 Ok(()) 60 } 61 }