use crate::{DataType, Error, Result};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct SimpleValue(pub(crate) u8);
impl SimpleValue {
pub const FALSE: Self = SimpleValue(20);
pub const TRUE: Self = SimpleValue(21);
pub const NULL: Self = SimpleValue(22);
pub fn new(value: impl TryInto<Self, Error = Error>) -> Self {
value.try_into().unwrap()
}
pub const fn from_u8(value: u8) -> Result<Self> {
let valid_range = value <= 23 || value >= 32;
if valid_range {
Ok(Self(value))
} else {
Err(Error::InvalidSimpleValue)
}
}
#[inline]
#[must_use]
pub const fn from_bool(value: bool) -> Self {
if value { Self::TRUE } else { Self::FALSE }
}
#[inline]
#[must_use]
pub const fn data_type(&self) -> DataType {
match self.0 {
20 | 21 => DataType::Bool,
22 => DataType::Null,
_ => DataType::Simple,
}
}
pub const fn to_bool(&self) -> Result<bool> {
match *self {
Self::FALSE => Ok(false),
Self::TRUE => Ok(true),
_ => Err(Error::InvalidSimpleValue),
}
}
#[must_use]
pub const fn to_u8(&self) -> u8 {
self.0
}
}
impl TryFrom<u8> for SimpleValue {
type Error = Error;
#[inline]
fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
Self::from_u8(value)
}
}
impl From<SimpleValue> for u8 {
#[inline]
fn from(value: SimpleValue) -> Self {
value.to_u8()
}
}
impl From<bool> for SimpleValue {
#[inline]
fn from(value: bool) -> Self {
Self::from_bool(value)
}
}
impl TryFrom<SimpleValue> for bool {
type Error = Error;
fn try_from(value: SimpleValue) -> std::result::Result<Self, Self::Error> {
value.to_bool()
}
}
impl From<()> for SimpleValue {
#[inline]
fn from(_: ()) -> Self {
Self::NULL
}
}