/ console / program / src / data / register / bytes.rs
bytes.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> FromBytes for Register<N> {
19      /// Reads the register from a buffer.
20      fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21          let variant = u8::read_le(&mut reader)?;
22          let locator = read_variable_length_integer(&mut reader)?;
23          match variant {
24              0 => Ok(Self::Locator(locator)),
25              1 => {
26                  // Read the number of accesses.
27                  let num_accesses = u16::read_le(&mut reader)?;
28                  if num_accesses as usize > N::MAX_DATA_DEPTH {
29                      return Err(error("Failed to deserialize register: Register access exceeds maximum depth"));
30                  }
31                  // Read the accesses.
32                  let accesses = (0..num_accesses).map(|_| Access::read_le(&mut reader)).collect::<IoResult<Vec<_>>>()?;
33                  Ok(Self::Access(locator, accesses))
34              }
35              2.. => Err(error(format!("Failed to deserialize register variant {variant}"))),
36          }
37      }
38  }
39  
40  impl<N: Network> ToBytes for Register<N> {
41      /// Writes the register to a buffer.
42      fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
43          match self {
44              Self::Locator(locator) => {
45                  u8::write_le(&0u8, &mut writer)?;
46                  variable_length_integer(locator).write_le(&mut writer)
47              }
48              Self::Access(locator, accesses) => {
49                  // Ensure the number of accesses is within the limit.
50                  if accesses.len() > N::MAX_DATA_DEPTH {
51                      return Err(error("Failed to serialize register: too many accesses"));
52                  }
53  
54                  u8::write_le(&1u8, &mut writer)?;
55                  variable_length_integer(locator).write_le(&mut writer)?;
56                  u16::try_from(accesses.len()).map_err(error)?.write_le(&mut writer)?;
57                  accesses.write_le(&mut writer)
58              }
59          }
60      }
61  }