148 lines
2.3 KiB
Rust
148 lines
2.3 KiB
Rust
use std::{
|
||
fmt,
|
||
ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign},
|
||
};
|
||
|
||
use crate::Size;
|
||
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct Vec2 {
|
||
pub x: usize,
|
||
pub y: usize,
|
||
}
|
||
|
||
impl Vec2 {
|
||
pub const fn new(x: usize, y: usize) -> Self {
|
||
Self { x, y }
|
||
}
|
||
|
||
pub fn to_size(self) -> Size {
|
||
Size {
|
||
width: self.x,
|
||
height: self.y,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl From<(usize, usize)> for Vec2 {
|
||
#[inline]
|
||
fn from(v: (usize, usize)) -> Vec2 {
|
||
Vec2 { x: v.0, y: v.1 }
|
||
}
|
||
}
|
||
|
||
impl From<Vec2> for (usize, usize) {
|
||
#[inline]
|
||
fn from(v: Vec2) -> (usize, usize) {
|
||
(v.x, v.y)
|
||
}
|
||
}
|
||
|
||
impl Add for Vec2 {
|
||
type Output = Vec2;
|
||
|
||
#[inline]
|
||
fn add(self, other: Vec2) -> Vec2 {
|
||
Vec2 {
|
||
x: self.x + other.x,
|
||
y: self.y + other.y,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl AddAssign for Vec2 {
|
||
#[inline]
|
||
fn add_assign(&mut self, other: Vec2) {
|
||
*self = Vec2 {
|
||
x: self.x + other.x,
|
||
y: self.y + other.y,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Sub for Vec2 {
|
||
type Output = Vec2;
|
||
|
||
#[inline]
|
||
fn sub(self, other: Vec2) -> Vec2 {
|
||
Vec2 {
|
||
x: self.x - other.x,
|
||
y: self.y - other.y,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl SubAssign for Vec2 {
|
||
#[inline]
|
||
fn sub_assign(&mut self, other: Vec2) {
|
||
*self = Vec2 {
|
||
x: self.x - other.x,
|
||
y: self.y - other.y,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Mul<usize> for Vec2 {
|
||
type Output = Vec2;
|
||
|
||
#[inline]
|
||
fn mul(self, other: usize) -> Vec2 {
|
||
Vec2 {
|
||
x: self.x * other,
|
||
y: self.y * other,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl MulAssign<usize> for Vec2 {
|
||
#[inline]
|
||
fn mul_assign(&mut self, other: usize) {
|
||
*self = Vec2 {
|
||
x: self.x * other,
|
||
y: self.y * other,
|
||
};
|
||
}
|
||
}
|
||
|
||
impl Mul<Vec2> for usize {
|
||
type Output = Vec2;
|
||
|
||
#[inline]
|
||
fn mul(self, other: Vec2) -> Vec2 {
|
||
other * self
|
||
}
|
||
}
|
||
|
||
impl Div<usize> for Vec2 {
|
||
type Output = Vec2;
|
||
|
||
/// Note: division by a scalar is implemented by multiplying by the reciprocal.
|
||
///
|
||
/// This is more efficient but has different roundoff behavior than division.
|
||
#[inline]
|
||
fn div(self, other: usize) -> Vec2 {
|
||
Self {
|
||
x: self.x / other,
|
||
y: self.y / other,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl DivAssign<usize> for Vec2 {
|
||
#[inline]
|
||
fn div_assign(&mut self, other: usize) {
|
||
self.x = self.x / other;
|
||
self.y = self.y / other;
|
||
}
|
||
}
|
||
|
||
impl fmt::Display for Vec2 {
|
||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||
write!(formatter, "𝐯=(")?;
|
||
fmt::Display::fmt(&self.x, formatter)?;
|
||
write!(formatter, ", ")?;
|
||
fmt::Display::fmt(&self.y, formatter)?;
|
||
write!(formatter, ")")
|
||
}
|
||
}
|