use crate::{ffi, Encode, Encoding, RefEncode};
use core::fmt;
#[repr(transparent)]
#[derive(Copy, Clone, Default)]
pub struct Bool {
value: ffi::BOOL,
}
impl Bool {
pub const YES: Self = Self::from_raw(ffi::YES);
pub const NO: Self = Self::from_raw(ffi::NO);
#[inline]
pub const fn new(value: bool) -> Self {
let value = value as ffi::BOOL;
Self { value }
}
#[inline]
pub const fn from_raw(value: ffi::BOOL) -> Self {
Self { value }
}
#[inline]
pub const fn as_raw(self) -> ffi::BOOL {
self.value
}
#[inline]
pub const fn is_false(self) -> bool {
self.value as u8 == 0
}
#[inline]
pub const fn is_true(self) -> bool {
self.value as u8 != 0
}
#[inline]
pub const fn as_bool(self) -> bool {
self.is_true()
}
}
impl From<bool> for Bool {
#[inline]
fn from(b: bool) -> Bool {
Bool::new(b)
}
}
impl From<Bool> for bool {
#[inline]
fn from(b: Bool) -> bool {
b.as_bool()
}
}
impl fmt::Debug for Bool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(if self.as_bool() { "YES" } else { "NO" })
}
}
unsafe impl Encode for Bool {
const ENCODING: Encoding<'static> = ffi::BOOL::ENCODING;
}
unsafe impl RefEncode for Bool {
const ENCODING_REF: Encoding<'static> = Encoding::Pointer(&Self::ENCODING);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic() {
let b = Bool::new(true);
assert!(b.as_bool());
assert!(b.is_true());
assert!(!b.is_false());
assert!(bool::from(b));
assert_eq!(b.as_raw() as usize, 1);
let b = Bool::new(false);
assert!(!b.as_bool());
assert!(!b.is_true());
assert!(b.is_false());
assert!(!bool::from(b));
assert_eq!(b.as_raw() as usize, 0);
}
#[test]
fn test_associated_constants() {
let b = Bool::YES;
assert!(b.as_bool());
assert!(b.is_true());
assert_eq!(b.as_raw() as usize, 1);
let b = Bool::NO;
assert!(!b.as_bool());
assert!(b.is_false());
assert_eq!(b.as_raw() as usize, 0);
}
#[test]
fn test_impls() {
let b: Bool = Default::default();
assert!(!b.as_bool());
assert!(b.is_false());
assert!(Bool::from(true).as_bool());
assert!(Bool::from(true).is_true());
assert!(Bool::from(false).is_false());
assert!(Bool::from(true).is_true());
assert!(Bool::from(false).is_false());
}
}