use crate::encode::Encode;
use alloc::borrow::Cow;
use core::fmt::Display;
use serde::{Deserialize, Serialize};
pub enum BoardValidationError {
EmptyName,
NameTooLong,
MinGtMax,
}
impl BoardValidationError {
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::EmptyName => "name must not be empty",
Self::NameTooLong => "name is too long",
Self::MinGtMax => "min must be less than or equal to max",
}
}
}
impl Display for BoardValidationError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct Boards<'a> {
#[serde(borrow)]
pub boards: Cow<'a, [Board<'a>]>,
}
impl<'a> Boards<'a> {
#[must_use]
pub const fn new(boards: Cow<'a, [Board<'a>]>) -> Self {
Self { boards }
}
}
impl<'a> Encode<'a> for Boards<'a> {}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct Board<'a> {
pub position: u16,
pub min: i16,
pub max: i16,
pub time: bool,
pub decimals: u8,
pub name: &'a str,
}
impl<'a> Board<'a> {
pub const fn validate(&self) -> Result<(), BoardValidationError> {
if self.name.is_empty() {
return Err(BoardValidationError::EmptyName);
}
if self.name.len() > 64 {
return Err(BoardValidationError::NameTooLong);
}
if self.min > self.max {
return Err(BoardValidationError::MinGtMax);
}
Ok(())
}
}