layout_engine/layout/
vec2.rs

1use std::iter::Sum;
2use std::ops::{Add, AddAssign, Sub, SubAssign};
3
4use crate::Orientation;
5
6#[derive(Clone, Debug, Copy, Default, PartialEq, Eq, Hash, Ord, PartialOrd)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub struct Vec2<T = usize> {
9    pub x: T,
10    pub y: T,
11}
12
13impl<T> Vec2<T> {
14    pub const fn new(x: T, y: T) -> Self {
15        Self { x, y }
16    }
17}
18
19impl<T: Copy> Vec2<T> {
20    /// Gets the `x` if `Orientation::Horizontal` else `y`
21    pub const fn in_orientation(&self, orientation: Orientation) -> T {
22        match orientation {
23            Orientation::Vertical => self.y,
24            Orientation::Horizontal => self.x,
25        }
26    }
27}
28
29impl Vec2 {
30    pub const fn saturating_sub(self, other: Self) -> Self {
31        Self {
32            x: self.x.saturating_sub(other.x),
33            y: self.y.saturating_sub(other.y),
34        }
35    }
36}
37
38impl<T: Add<Output = T>> Add for Vec2<T> {
39    type Output = Self;
40
41    fn add(self, other: Self) -> Self::Output {
42        Self {
43            x: self.x + other.x,
44            y: self.y + other.y,
45        }
46    }
47}
48
49impl<T: AddAssign<T>> AddAssign for Vec2<T> {
50    fn add_assign(&mut self, other: Self) {
51        self.x += other.x;
52        self.y += other.y;
53    }
54}
55
56impl<T: Sub<Output = T>> Sub for Vec2<T> {
57    type Output = Self;
58
59    fn sub(self, other: Self) -> Self::Output {
60        Self {
61            x: self.x - other.x,
62            y: self.y - other.y,
63        }
64    }
65}
66
67impl<T> Sum<Vec2<T>> for Vec2<T>
68where
69    T: AddAssign + Default,
70{
71    fn sum<I>(iter: I) -> Self
72    where
73        I: Iterator<Item = Self>,
74    {
75        let mut total = Self::default();
76        for i in iter {
77            total += i
78        }
79        total
80    }
81}
82
83impl<T: SubAssign<T>> SubAssign for Vec2<T> {
84    fn sub_assign(&mut self, other: Self) {
85        self.x -= other.x;
86        self.y -= other.y;
87    }
88}
89
90impl<T> From<(T, T)> for Vec2<T> {
91    fn from(value: (T, T)) -> Self {
92        Self {
93            x: value.0,
94            y: value.1,
95        }
96    }
97}