#[derive(Default, Clone, Copy, PartialEq)]
pub struct Length {
value: f64,
}
impl std::fmt::Debug for Length {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self}")
}
}
impl std::fmt::Display for Length {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}px", self.value)
}
}
impl Length {
pub const ZERO: Self = Self { value: 0. };
#[track_caller]
pub fn px(value: f64) -> Self {
if value < 0. || !value.is_finite() {
debug_panic!("Invalid length value '{value}'");
return Self::ZERO;
}
Self { value }
}
pub const fn try_px(value: f64) -> Option<Self> {
if value < 0. || !value.is_finite() {
return None;
}
Some(Self { value })
}
#[track_caller]
pub const fn const_px(value: f64) -> Self {
if value < 0. || !value.is_finite() {
panic!("Invalid length value");
}
Self { value }
}
pub const fn get(self) -> f64 {
self.value
}
pub const fn dp(self, scale: f64) -> f64 {
self.value * scale
}
pub const fn min(self, other: Self) -> Self {
if self.value < other.value {
self
} else {
other
}
}
pub const fn max(self, other: Self) -> Self {
if self.value > other.value {
self
} else {
other
}
}
pub const fn clamp(self, min: Self, max: Self) -> Self {
Self {
value: self.value.clamp(min.value, max.value),
}
}
pub const fn saturating_add(self, other: Self) -> Self {
Self {
value: (self.value + other.value).min(f64::MAX),
}
}
pub const fn saturating_sub(self, other: Self) -> Self {
Self {
value: (self.value - other.value).max(0.),
}
}
}