use super::Point2;
use crate::error::KikaError;
use core::ops::{Add, Mul, Neg, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vector2 {
x: f64,
y: f64,
}
impl Vector2 {
pub fn new(x: f64, y: f64) -> Result<Self, KikaError> {
if x.is_finite() && y.is_finite() {
Ok(Vector2 { x, y })
} else {
Err(KikaError::NonFiniteCoordinate)
}
}
pub(crate) fn new_unchecked(x: f64, y: f64) -> Self {
Vector2 { x, y }
}
#[inline]
pub fn x(&self) -> f64 {
self.x
}
#[inline]
pub fn y(&self) -> f64 {
self.y
}
}
impl Add for Vector2 {
type Output = Vector2;
fn add(self, rhs: Vector2) -> Vector2 {
Vector2 {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl Sub for Vector2 {
type Output = Vector2;
fn sub(self, rhs: Vector2) -> Vector2 {
Vector2 {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
impl Neg for Vector2 {
type Output = Vector2;
fn neg(self) -> Vector2 {
Vector2 {
x: -self.x,
y: -self.y,
}
}
}
impl Mul<f64> for Vector2 {
type Output = Vector2;
fn mul(self, rhs: f64) -> Vector2 {
Vector2 {
x: self.x * rhs,
y: self.y * rhs,
}
}
}
impl Add<Vector2> for Point2 {
type Output = Point2;
fn add(self, rhs: Vector2) -> Point2 {
Point2::new_unchecked(self.x() + rhs.x, self.y() + rhs.y)
}
}
impl Sub<Vector2> for Point2 {
type Output = Point2;
fn sub(self, rhs: Vector2) -> Point2 {
Point2::new_unchecked(self.x() - rhs.x, self.y() - rhs.y)
}
}
impl Sub for Point2 {
type Output = Vector2;
fn sub(self, rhs: Point2) -> Vector2 {
Vector2 {
x: self.x() - rhs.x(),
y: self.y() - rhs.y(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn v(x: f64, y: f64) -> Vector2 {
Vector2::new(x, y).unwrap()
}
fn p(x: f64, y: f64) -> Point2 {
Point2::new(x, y).unwrap()
}
#[test]
fn rejects_non_finite() {
assert_eq!(
Vector2::new(f64::NAN, 0.0),
Err(KikaError::NonFiniteCoordinate)
);
assert_eq!(
Vector2::new(0.0, f64::INFINITY),
Err(KikaError::NonFiniteCoordinate)
);
}
#[test]
fn point_vector_affine_arithmetic() {
assert_eq!(p(1.0, 2.0) + v(3.0, 4.0), p(4.0, 6.0));
assert_eq!(p(4.0, 6.0) - v(3.0, 4.0), p(1.0, 2.0));
assert_eq!(p(4.0, 6.0) - p(1.0, 2.0), v(3.0, 4.0));
}
#[test]
fn vector_arithmetic() {
assert_eq!(v(1.0, 2.0) + v(3.0, 4.0), v(4.0, 6.0));
assert_eq!(v(3.0, 4.0) - v(1.0, 2.0), v(2.0, 2.0));
assert_eq!(-v(1.0, -2.0), v(-1.0, 2.0));
assert_eq!(v(1.0, 2.0) * 3.0, v(3.0, 6.0));
}
}