Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Add and Sub traits for Size2D #166

Merged
merged 1 commit into from Sep 19, 2016
Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file
Failed to load files.

Always

Just for now

Implement Add and Sub traits for Size2D

This is useful for doing some basic operations in Servo.
  • Loading branch information
mrobinson committed Sep 19, 2016
commit 666202b15878d623f4ae39d1062a03cd676be6a5
@@ -14,7 +14,7 @@ use num::*;

use num_traits::NumCast;
use std::fmt;
use std::ops::{Mul, Div};
use std::ops::{Add, Div, Mul, Sub};
use std::marker::PhantomData;

/// A 2d size tagged with a unit.
@@ -88,6 +88,20 @@ impl<T: Floor, U> TypedSize2D<T, U> {
}
}

impl<T: Copy + Add<T, Output=T>, U> Add for TypedSize2D<T, U> {
type Output = TypedSize2D<T, U>;
fn add(self, other: TypedSize2D<T, U>) -> TypedSize2D<T, U> {
TypedSize2D::new(self.width + other.width, self.height + other.height)
}
}

impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedSize2D<T, U> {
type Output = TypedSize2D<T, U>;
fn sub(self, other: TypedSize2D<T, U>) -> TypedSize2D<T, U> {
TypedSize2D::new(self.width - other.width, self.height - other.height)
}
}

impl<T: Copy + Clone + Mul<T, Output=U>, U> TypedSize2D<T, U> {
pub fn area(&self) -> U { self.width * self.height }
}
@@ -212,3 +226,46 @@ impl<T: NumCast + Copy, Unit> TypedSize2D<T, Unit> {
self.cast().unwrap()
}
}

#[cfg(test)]
mod size2d {
use super::Size2D;

#[test]
pub fn test_add() {
let p1 = Size2D::new(1.0, 2.0);
let p2 = Size2D::new(3.0, 4.0);
assert_eq!(p1 + p2, Size2D::new(4.0, 6.0));

let p1 = Size2D::new(1.0, 2.0);
let p2 = Size2D::new(0.0, 0.0);
assert_eq!(p1 + p2, Size2D::new(1.0, 2.0));

let p1 = Size2D::new(1.0, 2.0);
let p2 = Size2D::new(-3.0, -4.0);
assert_eq!(p1 + p2, Size2D::new(-2.0, -2.0));

let p1 = Size2D::new(0.0, 0.0);
let p2 = Size2D::new(0.0, 0.0);
assert_eq!(p1 + p2, Size2D::new(0.0, 0.0));
}

#[test]
pub fn test_sub() {
let p1 = Size2D::new(1.0, 2.0);
let p2 = Size2D::new(3.0, 4.0);
assert_eq!(p1 - p2, Size2D::new(-2.0, -2.0));

let p1 = Size2D::new(1.0, 2.0);
let p2 = Size2D::new(0.0, 0.0);
assert_eq!(p1 - p2, Size2D::new(1.0, 2.0));

let p1 = Size2D::new(1.0, 2.0);
let p2 = Size2D::new(-3.0, -4.0);
assert_eq!(p1 - p2, Size2D::new(4.0, 6.0));

let p1 = Size2D::new(0.0, 0.0);
let p2 = Size2D::new(0.0, 0.0);
assert_eq!(p1 - p2, Size2D::new(0.0, 0.0));
}
}
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.