skunk2d/src/vec2.rs

111 lines
2.5 KiB
Rust

use num::{Num, ToPrimitive};
use std::cmp::Ordering;
use std::cmp::Ordering::{Greater, Less};
use std::iter::Step;
use std::ops::{Add, AddAssign, Range, Sub, SubAssign};
use Ordering::Equal;
#[derive(Copy, Clone)]
pub struct Vec2<T: Num + Copy + ToPrimitive> {
pub x: T,
pub y: T,
}
pub struct Vec2Iter<T: Num + Copy + ToPrimitive> {
start: Vec2<T>,
end: Vec2<T>,
current: Vec2<T>,
}
impl<T: Num + Copy + ToPrimitive> Vec2<T> {
//pub static
pub fn zero() -> Self {
Vec2 {
x: T::zero(),
y: T::zero(),
}
}
//pub
pub fn iter_to(self, other: Self) -> Vec2Iter<T> {
Vec2Iter {
start: self,
end: other,
current: Vec2 {
x: self.x - T::one(),
y: self.y,
},
}
}
pub fn size(&self) -> usize {
(self.x * self.y).to_usize().unwrap()
}
}
impl<T: Num + Copy + ToPrimitive + Default> Default for Vec2<T> {
fn default() -> Self {
Vec2 {
x: T::default(),
y: T::default(),
}
}
}
impl<T: Num + Copy + ToPrimitive> PartialEq for Vec2<T> {
fn eq(&self, other: &Self) -> bool {
self.x == other.x && self.y == other.y
}
}
impl<T: Num + Copy + ToPrimitive + PartialOrd> Iterator for Vec2Iter<T> {
type Item = Vec2<T>;
fn next(&mut self) -> Option<Self::Item> {
self.current.x = self.current.x + T::one();
if self.current.x >= self.end.x {
self.current.y = self.current.y + T::one();
self.current.x = self.start.x;
if self.current.y >= self.end.y {
return None;
}
}
Some(self.current)
}
}
impl<T: Num + Copy + ToPrimitive> Add for Vec2<T> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl<T: Num + Copy + ToPrimitive> Sub for Vec2<T> {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
impl<T: Num + Copy + ToPrimitive + AddAssign> AddAssign for Vec2<T> {
fn add_assign(&mut self, rhs: Self) {
self.x += rhs.x;
self.y += rhs.y;
}
}
impl<T: Num + Copy + ToPrimitive + SubAssign> SubAssign for Vec2<T> {
fn sub_assign(&mut self, rhs: Self) {
self.x -= rhs.x;
self.y -= rhs.y;
}
}