use crate::Length;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Edges<T> {
pub left: T,
pub top: T,
pub right: T,
pub bottom: T,
}
impl<T> Edges<T> {
pub fn map<U>(self, mut f: impl FnMut(T) -> U) -> Edges<U> {
Edges {
left: f(self.left),
top: f(self.top),
right: f(self.right),
bottom: f(self.bottom),
}
}
pub fn with<U, V>(self, other: Edges<U>, mut f: impl FnMut(T, U) -> V) -> Edges<V> {
Edges {
left: f(self.left, other.left),
top: f(self.top, other.top),
right: f(self.right, other.right),
bottom: f(self.bottom, other.bottom),
}
}
}
impl Edges<Length> {
#[must_use]
pub fn placed(x: Length, y: Length, width: Length, height: Length) -> Option<Self> {
Some(Self {
left: x,
top: y,
right: x.checked_add(width)?,
bottom: y.checked_add(height)?,
})
}
#[must_use]
pub const fn sized(width: Length, height: Length) -> Self {
Self {
left: Length::ZERO,
top: Length::ZERO,
right: width,
bottom: height,
}
}
#[must_use]
pub fn width(self) -> Length {
self.right - self.left
}
#[must_use]
pub fn height(self) -> Length {
self.bottom - self.top
}
}
impl<T> From<[T; 4]> for Edges<T> {
fn from([left, top, right, bottom]: [T; 4]) -> Self {
Self {
left,
top,
right,
bottom,
}
}
}
#[cfg(test)]
mod tests {
use super::Edges;
use crate::Length;
#[test]
fn makes_a_box_from_its_corner_and_its_size() {
let units = Length::from_units;
let placed = Edges::placed(units(10), units(-20), units(30), units(40)).unwrap();
assert_eq!(placed, Edges::from([10, -20, 40, 20].map(units)));
assert_eq!((placed.width(), placed.height()), (units(30), units(40)));
let sized = Edges::sized(units(30), units(40));
assert_eq!(sized, Edges::from([0, 0, 30, 40].map(units)));
assert_eq!((sized.width(), sized.height()), (units(30), units(40)));
let far = units(i64::MAX - 5);
assert_eq!(Edges::placed(far, units(0), units(10), units(1)), None);
assert_eq!(Edges::placed(units(0), far, units(1), units(10)), None);
}
#[test]
fn keeps_each_value_on_its_edge() {
let edges = Edges::from([1, 2, 3, 4]);
assert_eq!(
(edges.left, edges.top, edges.right, edges.bottom),
(1, 2, 3, 4)
);
assert_eq!(edges.map(|value| value * 10), Edges::from([10, 20, 30, 40]));
assert_eq!(
edges.with(Edges::from([100; 4]), |a, b| a + b),
Edges::from([101, 102, 103, 104])
);
}
}