Some Macros

This commit is contained in:
Stephan Rehfeld 2026-06-17 18:50:47 +02:00
parent 4f762c7df9
commit 8aeb643e21
2 changed files with 30 additions and 30 deletions

View File

@ -124,4 +124,7 @@ fn main() {
); );
println!("Reference counter = {}", Rc::strong_count(&tex)); println!("Reference counter = {}", Rc::strong_count(&tex));
let a = Vector3::new(2.0, 3.0, 1.0);
let b = 10.0 * a;
} }

View File

@ -1,17 +1,23 @@
use std::ops::{Add, Div, Mul, Sub}; use std::ops::{Add, Div, Mul, Sub};
#[derive(Copy, Clone, PartialEq, Debug)] macro_rules! create_vector {
pub struct Vector3<T> { ($name:ident [$($elem:ident),+] ) => {
x: T, #[derive(Copy, Clone, PartialEq, Debug)]
y: T, pub struct $name<T> {
z: T, $($elem: T,)*
}
impl<T> $name<T> {
pub fn new($($elem : T,)*) -> $name<T> {
$name { $($elem,)* }
}
}
};
} }
impl<T> Vector3<T> { create_vector! { Vector4 [x, y, z, w] }
pub fn new(x: T, y: T, z: T) -> Vector3<T> { create_vector! { Vector3 [x, y, z] }
Vector3 { x, y, z } create_vector! { Vector2 [x, y] }
}
}
impl<T> Add for Vector3<T> impl<T> Add for Vector3<T>
where where
@ -46,29 +52,20 @@ where
} }
} }
impl Mul<Vector3<f64>> for f64 { macro_rules! impl_mul_for_vector3 {
type Output = Vector3<f64>; ($($type:ty)+) => {
$(
impl Mul<Vector3<$type>> for $type {
type Output = Vector3<$type>;
fn mul(self, rhs: Vector3<f64>) -> Self::Output { fn mul(self, rhs: Vector3<$type>) -> Self::Output {
Vector3::new(self * rhs.x, self * rhs.y, self * rhs.z) Vector3::new(self * rhs.x, self * rhs.y, self * rhs.z)
} }
})*
};
} }
impl Mul<Vector3<f32>> for f32 { impl_mul_for_vector3! { i32 f32 f64 }
type Output = Vector3<f32>;
fn mul(self, rhs: Vector3<f32>) -> Self::Output {
Vector3::new(self * rhs.x, self * rhs.y, self * rhs.z)
}
}
impl Mul<Vector3<i32>> for i32 {
type Output = Vector3<i32>;
fn mul(self, rhs: Vector3<i32>) -> Self::Output {
Vector3::new(self * rhs.x, self * rhs.y, self * rhs.z)
}
}
impl<T> Mul for Vector3<T> impl<T> Mul for Vector3<T>
where where