use std::borrow::Cow;
use std::fmt;
use std::num::NonZeroU16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Length {
Cells(u16),
Fill(NonZeroU16),
}
impl Length {
pub const fn fill(weight: u16) -> Self {
match Self::try_fill(weight) {
Ok(length) => length,
Err(_) => panic!("fill weight must be greater than zero"),
}
}
pub const fn try_fill(weight: u16) -> Result<Self, InvalidFillWeight> {
match NonZeroU16::new(weight) {
Some(weight) => Ok(Self::Fill(weight)),
None => Err(InvalidFillWeight),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidFillWeight;
impl fmt::Display for InvalidFillWeight {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("fill weight must be greater than zero")
}
}
impl std::error::Error for InvalidFillWeight {}
impl From<u16> for Length {
fn from(value: u16) -> Self {
Self::Cells(value)
}
}
#[cfg(test)]
mod length_tests {
use super::{InvalidFillWeight, Length};
#[test]
fn fill_and_try_fill_construct_the_same_positive_weight() {
assert_eq!(Length::fill(1), Length::try_fill(1).unwrap());
assert_eq!(Length::fill(2), Length::try_fill(2).unwrap());
}
#[test]
fn try_fill_rejects_zero() {
assert_eq!(Length::try_fill(0), Err(InvalidFillWeight));
}
#[test]
#[should_panic(expected = "fill weight must be greater than zero")]
fn fill_panics_on_zero() {
Length::fill(0);
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Overflow {
#[default]
Wrap,
Clip(Cow<'static, str>),
}
impl Overflow {
pub const fn clip() -> Self {
Self::Clip(Cow::Borrowed(""))
}
pub const fn ellipsis() -> Self {
Self::Clip(Cow::Borrowed("…"))
}
pub fn clip_with(marker: impl Into<Cow<'static, str>>) -> Self {
Self::Clip(marker.into())
}
pub fn clip_marker(&self) -> Option<&str> {
match self {
Self::Wrap => None,
Self::Clip(marker) => Some(marker),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Align {
#[default]
Left,
Center,
Right,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum VerticalAlign {
#[default]
Top,
Center,
Bottom,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Sides {
pub top: u16,
pub right: u16,
pub bottom: u16,
pub left: u16,
}
impl From<u16> for Sides {
fn from(value: u16) -> Self {
Self {
top: value,
right: value,
bottom: value,
left: value,
}
}
}
impl From<(u16, u16)> for Sides {
fn from((vertical, horizontal): (u16, u16)) -> Self {
Self {
top: vertical,
right: horizontal,
bottom: vertical,
left: horizontal,
}
}
}
impl From<(u16, u16, u16, u16)> for Sides {
fn from((top, right, bottom, left): (u16, u16, u16, u16)) -> Self {
Self {
top,
right,
bottom,
left,
}
}
}