Vector Space

A minimal, stable foundation for generic vector math in Rust. Provides the VectorSpace trait.
Designed as a general-purpose base for any vector-like type. Its simplicity ensures compatibility across libraries. It can be used as a compatibility layer between different vector math, physics, and rendering libraries.
Implement once, use everywhere.
Key Components
VectorSpace: Trait defining a Scalar type, that can be implemented for types that have the properties of a vector space (Add, Sub, Mul, Div, Neg, Zero).
VectorSpaceAssign: Automatically implemented trait for types that implement VectorSpace and the proper assign traits (AddAssign, SubAssign, MulAssign, DivAssign).
AffineSpace: Represents a type whose difference is a vector type, like points.
interpolate: Interpolates between two points.
Features
- Universal for any
Scalar-typed structure.
- Efficient: No allocations.
- Flexible ops: Blanket impls for scalars (
f32, f64).
Example
use std::ops::{Add, Div, Mul, Neg, Sub};
use num_traits::Zero;
use vector_space::{VectorSpace, interpolate};
#[derive(Clone, Copy, PartialEq, Debug)]
struct Vector {
x: f32,
y: f32,
}
impl Vector {
fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
impl Add for Vector {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Sub for Vector {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Mul<f32> for Vector {
type Output = Self;
fn mul(self, other: f32) -> Self {
Self {
x: self.x * other,
y: self.y * other,
}
}
}
impl Div<f32> for Vector {
type Output = Self;
fn div(self, other: f32) -> Self {
Self {
x: self.x / other,
y: self.y / other,
}
}
}
impl Neg for Vector {
type Output = Self;
fn neg(self) -> Self {
Self {
x: -self.x,
y: -self.y,
}
}
}
impl Zero for Vector {
fn zero() -> Self {
Self { x: 0.0, y: 0.0 }
}
fn is_zero(&self) -> bool {
self.x == 0.0 && self.y == 0.0
}
}
impl VectorSpace for Vector {
type Scalar = f32;
}
let a = Vector::new(-1.0, 2.0);
let b = Vector::new(3.0, 6.0);
assert_eq!(interpolate(a, b, 0.75), Vector::new(2.0, 5.0));