ton_net_cell/slice/
address.rs1use super::Slice;
12use crate::error::CellError;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum MsgAddress {
17 None,
19 Std {
21 workchain: i8,
23 account: [u8; 32],
25 },
26}
27
28impl Slice<'_> {
29 pub fn load_address(&mut self) -> Result<MsgAddress, CellError> {
41 match self.load_uint(2)? {
42 0b00 => Ok(MsgAddress::None),
43 0b10 => {
44 if self.load_bit()? {
45 return Err(CellError::Malformed("anycast address is not supported"));
46 }
47 #[allow(
48 clippy::cast_possible_truncation,
49 reason = "load_int(8) yields a value in i8 range"
50 )]
51 let workchain = self.load_int(8)? as i8;
52 let account = self
53 .load_bytes(32)?
54 .try_into()
55 .map_err(|_| CellError::Malformed("address is not thirty-two bytes"))?;
56 Ok(MsgAddress::Std { workchain, account })
57 }
58 _ => Err(CellError::Malformed(
59 "external and variable addresses are not supported",
60 )),
61 }
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68 use crate::Builder;
69
70 fn round_trip(address: &MsgAddress) -> MsgAddress {
72 let mut builder = Builder::new();
73 builder.store_address(address).expect("an address fits");
74 let cell = builder.build().expect("the cell is well formed");
75 cell.parse().load_address().expect("the address reads back")
76 }
77
78 #[test]
79 fn the_none_form_round_trips() {
80 assert_eq!(round_trip(&MsgAddress::None), MsgAddress::None);
81 }
82
83 #[test]
84 fn the_standard_form_round_trips() {
85 for (workchain, fill) in [(0i8, 0x00u8), (-1, 0xff), (1, 0x11)] {
86 let address = MsgAddress::Std {
87 workchain,
88 account: [fill; 32],
89 };
90 assert_eq!(round_trip(&address), address);
91 }
92 }
93
94 #[test]
95 fn an_anycast_address_is_refused() {
96 let mut builder = Builder::new();
98 builder.store_uint(0b10, 2).expect("the tag fits");
99 builder.store_bit(true).expect("the anycast bit fits");
100 builder.store_int(0, 8).expect("a workchain fits");
101 builder.store_bytes(&[0u8; 32]).expect("an account fits");
102 let cell = builder.build().expect("the cell is well formed");
103 assert_eq!(
104 cell.parse().load_address(),
105 Err(CellError::Malformed("anycast address is not supported"))
106 );
107 }
108
109 #[test]
110 fn an_external_address_is_refused() {
111 let mut builder = Builder::new();
112 builder.store_uint(0b01, 2).expect("the tag fits");
113 let cell = builder.build().expect("the cell is well formed");
114 assert_eq!(
115 cell.parse().load_address(),
116 Err(CellError::Malformed(
117 "external and variable addresses are not supported"
118 ))
119 );
120 }
121}