From 0487bdb465dd0c484cb6f1426bf1cf17d3c9e751 Mon Sep 17 00:00:00 2001 From: Joscha Date: Sat, 2 Mar 2024 23:36:21 +0100 Subject: [PATCH] Add Vec2 --- showbits-common/src/lib.rs | 6 +- showbits-common/src/vec2.rs | 87 ++++++++++++++++++++++++++++ showbits-thermal-printer/src/main.rs | 4 +- 3 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 showbits-common/src/vec2.rs diff --git a/showbits-common/src/lib.rs b/showbits-common/src/lib.rs index 9277de0..e63189e 100644 --- a/showbits-common/src/lib.rs +++ b/showbits-common/src/lib.rs @@ -1,3 +1,3 @@ -pub fn greet(who: &str) { - println!("Hello {who}!"); -} +pub use crate::vec2::Vec2; + +mod vec2; diff --git a/showbits-common/src/vec2.rs b/showbits-common/src/vec2.rs new file mode 100644 index 0000000..1660e6d --- /dev/null +++ b/showbits-common/src/vec2.rs @@ -0,0 +1,87 @@ +use std::{ + fmt, + ops::{Add, Mul, Neg, Sub}, +}; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Vec2 { + pub x: i32, + pub y: i32, +} + +impl Vec2 { + pub const ZERO: Self = Self::new(0, 0); + pub const NORTH: Self = Self::new(0, -1); + pub const SOUTH: Self = Self::new(0, 1); + pub const WEST: Self = Self::new(-1, 0); + pub const EAST: Self = Self::new(1, 0); + + pub const fn new(x: i32, y: i32) -> Self { + Self { x, y } + } + + pub fn to(self, other: Self) -> Self { + other - self + } +} + +impl fmt::Debug for Vec2 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Vec2").field(&self.x).field(&self.y).finish() + } +} + +impl Neg for Vec2 { + type Output = Self; + + fn neg(self) -> Self::Output { + Self { + x: -self.x, + y: -self.y, + } + } +} + +impl Add for Vec2 { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + x: self.x + rhs.x, + y: self.y + rhs.y, + } + } +} + +impl Sub for Vec2 { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self { + x: self.x - rhs.x, + y: self.y - rhs.y, + } + } +} + +impl Mul for Vec2 { + type Output = Self; + + fn mul(self, rhs: i32) -> Self::Output { + Self { + x: self.x * rhs, + y: self.y * rhs, + } + } +} + +impl Mul for Vec2 { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + Self { + x: self.x * rhs.x, + y: self.y * rhs.y, + } + } +} diff --git a/showbits-thermal-printer/src/main.rs b/showbits-thermal-printer/src/main.rs index a844748..bed65fa 100644 --- a/showbits-thermal-printer/src/main.rs +++ b/showbits-thermal-printer/src/main.rs @@ -1,3 +1,5 @@ +use showbits_common::Vec2; + fn main() { - showbits_common::greet("world"); + println!("{:?}", Vec2::EAST); }