multiversx_sc_codec/impl_for_types/
impl_bool.rs

1use crate::{
2    dep_encode_num_mimic, DecodeError, DecodeErrorHandler, EncodeErrorHandler, NestedDecode,
3    NestedDecodeInput, NestedEncode, NestedEncodeOutput, TopDecode, TopDecodeInput, TopEncode,
4    TopEncodeOutput,
5};
6
7impl TopEncode for bool {
8    #[inline]
9    fn top_encode_or_handle_err<O, H>(&self, output: O, _h: H) -> Result<(), H::HandledErr>
10    where
11        O: TopEncodeOutput,
12        H: EncodeErrorHandler,
13    {
14        // only using signed because this one is implemented in Arwen, unsigned is not
15        // TODO: change to set_u64
16        // true -> 1i64
17        // false -> 0i64
18        output.set_i64(i64::from(*self));
19        Ok(())
20    }
21}
22
23impl TopDecode for bool {
24    fn top_decode_or_handle_err<I, H>(input: I, h: H) -> Result<Self, H::HandledErr>
25    where
26        I: TopDecodeInput,
27        H: DecodeErrorHandler,
28    {
29        match input.into_u64(h)? {
30            0 => Ok(false),
31            1 => Ok(true),
32            _ => Err(h.handle_error(DecodeError::INPUT_OUT_OF_RANGE)),
33        }
34    }
35}
36
37dep_encode_num_mimic! {bool, u8}
38
39impl NestedDecode for bool {
40    fn dep_decode_or_handle_err<I, H>(input: &mut I, h: H) -> Result<Self, H::HandledErr>
41    where
42        I: NestedDecodeInput,
43        H: DecodeErrorHandler,
44    {
45        match input.read_byte(h)? {
46            0 => Ok(false),
47            1 => Ok(true),
48            _ => Err(h.handle_error(DecodeError::INVALID_VALUE)),
49        }
50    }
51}
52
53#[cfg(test)]
54pub mod tests {
55    use crate::test_util::{check_dep_encode_decode, check_top_encode_decode};
56
57    #[test]
58    fn test_top() {
59        check_top_encode_decode(true, &[1]);
60        check_top_encode_decode(false, &[]);
61    }
62    #[test]
63    fn test_dep() {
64        check_dep_encode_decode(true, &[1]);
65        check_dep_encode_decode(false, &[0]);
66    }
67}