Skip to main content

flatty_portable/
bool_.rs

1use crate::{NativeCast, Portable};
2use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};
3use flatty_base::{
4    error::{Error, ErrorKind},
5    traits::{Flat, FlatValidate},
6};
7
8/// Boolean type that has portable binary representation.
9#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
10#[repr(u8)]
11pub enum Bool {
12    #[default]
13    False = 0,
14    True = 1,
15}
16
17impl From<bool> for Bool {
18    fn from(value: bool) -> Self {
19        match value {
20            true => Bool::True,
21            false => Bool::False,
22        }
23    }
24}
25
26impl From<Bool> for bool {
27    fn from(value: Bool) -> Self {
28        match value {
29            Bool::True => true,
30            Bool::False => false,
31        }
32    }
33}
34
35unsafe impl FlatValidate for Bool {
36    unsafe fn validate_unchecked(bytes: &[u8]) -> Result<(), Error> {
37        match bytes.get_unchecked(0) {
38            0..=1 => Ok(()),
39            _ => Err(Error {
40                kind: ErrorKind::InvalidData,
41                pos: 0,
42            }),
43        }
44    }
45}
46
47unsafe impl Flat for Bool {}
48
49unsafe impl Portable for Bool {}
50
51impl NativeCast for Bool {
52    type Native = bool;
53
54    fn from_native(n: bool) -> Self {
55        n.into()
56    }
57    fn to_native(&self) -> bool {
58        (*self).into()
59    }
60}
61
62impl Not for Bool {
63    type Output = Self;
64    fn not(self) -> Self::Output {
65        bool::from(self).not().into()
66    }
67}
68
69impl BitAnd for Bool {
70    type Output = Self;
71    fn bitand(self, rhs: Self) -> Self::Output {
72        bool::from(self).bitand(bool::from(rhs)).into()
73    }
74}
75
76impl BitOr for Bool {
77    type Output = Self;
78    fn bitor(self, rhs: Self) -> Self::Output {
79        bool::from(self).bitor(bool::from(rhs)).into()
80    }
81}
82
83impl BitXor for Bool {
84    type Output = Self;
85    fn bitxor(self, rhs: Self) -> Self::Output {
86        bool::from(self).bitxor(bool::from(rhs)).into()
87    }
88}
89
90impl BitAndAssign for Bool {
91    fn bitand_assign(&mut self, rhs: Self) {
92        *self = self.bitand(rhs);
93    }
94}
95
96impl BitOrAssign for Bool {
97    fn bitor_assign(&mut self, rhs: Self) {
98        *self = self.bitor(rhs);
99    }
100}
101
102impl BitXorAssign for Bool {
103    fn bitxor_assign(&mut self, rhs: Self) {
104        *self = self.bitxor(rhs);
105    }
106}