wipe/src/vec.rs

79 lines
1.6 KiB
Rust
Raw Normal View History

2022-04-08 16:59:52 +00:00
use std::ops::Sub;
2022-04-03 10:30:36 +00:00
/// A vector with a x and y axis.
2022-04-02 15:23:19 +00:00
#[derive(Copy, Clone)]
pub struct Vector {
pub x: f32,
pub y: f32
}
impl Vector {
2022-04-03 12:43:14 +00:00
pub const ZERO: Vector = Vector::new(0.0, 0.0);
pub const fn new(x: f32, y: f32) -> Self {
2022-04-02 15:23:19 +00:00
Self { x, y }
}
2022-04-08 16:59:52 +00:00
pub fn center(self) -> Self {
Self::new(self.x / 2.0, self.y / 2.0)
}
pub fn length(self) -> f32 {
(self.x * self.x + self.y * self.y).sqrt()
}
2022-04-03 10:30:36 +00:00
/// Creates a vector with the on screen coordinates based on the terminal coordinates.
/// # Arguments
/// * `x`: The x axis of the terminal character.
/// * `y`: The y axis of the terminal character.
2022-04-02 15:23:19 +00:00
pub fn from_terminal(x: usize, y: usize) -> Self {
2022-04-03 12:43:14 +00:00
Self::new(x as f32, y as f32 * 2.0)
}
}
2022-04-08 16:59:52 +00:00
impl Sub for Vector {
type Output = Vector;
fn sub(self, rhs: Self) -> Self::Output {
Vector::new(self.x - rhs.x, self.y - rhs.y)
}
}
2022-04-03 12:43:14 +00:00
#[cfg(test)]
mod test {
use super::*;
#[test]
fn new() {
let vec = Vector::new(3.0, 5.0);
assert_eq!(3.0, vec.x);
assert_eq!(5.0, vec.y);
}
#[test]
fn from_terminal() {
let vec = Vector::from_terminal(2, 4);
assert_eq!(2.0, vec.x);
assert_eq!(8.0, vec.y);
}
#[test]
fn copy() {
let vec = Vector::new(2.0, 4.0);
let copy = vec;
assert_eq!(vec.x, copy.x);
assert_eq!(vec.y, copy.y);
}
#[test]
fn clone() {
let vec = Vector::new(2.0, 4.0);
let clone = vec.clone();
assert_eq!(vec.x, clone.x);
assert_eq!(vec.y, clone.y);
2022-04-02 15:23:19 +00:00
}
}