Skip to content

Commit

Permalink
Overload * and / for Point
Browse files Browse the repository at this point in the history
  • Loading branch information
thomas-fred committed Aug 15, 2024
1 parent 5f911da commit f42589f
Showing 1 changed file with 52 additions and 5 deletions.
57 changes: 52 additions & 5 deletions extension-rust/src/geometry.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ops::{Add, Sub};
use std::ops::{Add, Sub, Mul, Div};

#[derive(Debug, PartialEq)]
pub struct Point {
Expand All @@ -10,32 +10,79 @@ impl Point {
fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
fn magnitude(self) -> f64 {
(self.x * self.x + self.y * self.y).sqrt()
}
}

impl Add for Point {
type Output = Self;

fn add(self, other: Self) -> Self {
Self {x: self.x + other.x, y: self.y + other.y}
}
}

impl Sub for Point {
type Output = Self;

fn sub(self, other: Self) -> Self {
Self {x: self.x - other.x, y: self.y - other.y}
}
}

impl Mul<f64> for Point {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self {x: self.x * other, y: self.y * other}
}
}

impl Mul<Point> for f64 {
type Output = Point;
fn mul(self, other: Point) -> Point {
Point {x: self * other.x, y: self * other.y}
}
}

impl Div<f64> for Point {
type Output = Self;
fn div(self, other: f64) -> Self {
Self {x: self.x / other, y: self.y / other}
}
}

mod tests {
use super::*;

#[test]
fn test_add() {
fn magnitude() {
assert_eq!(5.0, Point{y: 3.0, x: 4.0}.magnitude());
assert_eq!(13.0, Point{y: 5.0, x: 12.0}.magnitude());
assert_eq!(65.0, Point{y: -33.0, x: -56.0}.magnitude());
}

#[test]
fn add() {
let a = Point{x: 1.0, y: 2.0};
let b = Point{x: 1.0, y: 0.0};
assert_eq!(a + b, Point{x: 2.0, y: 2.0});
}

#[test]
fn subtract() {
let a = Point{x: 1.0, y: 2.0};
let b = Point{x: 1.0, y: 0.0};
assert_eq!(a + b, Point{x: 2.0, y: 2.0})
assert_eq!(b - a, Point{x: 0.0, y: -2.0});
}

#[test]
fn mul() {
assert_eq!(Point{x: 1.3, y: 2.0} * 4.0, Point{x: 5.2, y: 8.0});
assert_eq!(4.0 * Point{x: 1.3, y: 2.0}, Point{x: 5.2, y: 8.0});
}

#[test]
fn div() {
assert_eq!(Point{x: 7.0, y: 2.0} / 2.0, Point{x: 3.5, y: 1.0});
}

}

0 comments on commit f42589f

Please sign in to comment.