embedded-vector 0.2.1

2D, 3D, and 4D f32 vectors for no_std embedded systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Copyright (C) 2026 Jorge Andre Castro
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 2 of the License, or (at your option)
// any later version.

//! # embedded-vector
//!
//! 2D, 3D, and 4D `f32` vectors for `no_std` embedded systems.
//!
//! No standard-library dependency, no `unsafe`, no allocation, and no panics.
//! Uses [`embedded_f32_sqrt`] for square-root calculations.
//!
//! ## Quick start
//!
//! ```rust
//! use embedded_vector::{Vec3, Vec4};
//!
//! let a = Vec3::new(1.0, 2.0, 3.0);
//! let b = Vec3::new(4.0, 5.0, 6.0);
//!
//! assert_eq!(a + b, Vec3::new(5.0, 7.0, 9.0));
//! assert_eq!(a.dot(&b), 32.0);
//! assert_eq!(a.cross(&b), Vec3::new(-3.0, 6.0, -3.0));
//!
//! let n = a.norm().unwrap();              // √14 ≈ 3.742
//! let u = a.normalize().unwrap();         // Unit vector
//! assert!((u.norm().unwrap() - 1.0).abs() < 1e-5);
//!
//! // Homogeneous coordinates
//! let p = Vec4::from_vec3(a, 2.0);
//! assert_eq!(p.perspective_divide().unwrap(), Vec3::new(0.5, 1.0, 1.5));
//! # let _ = n;
//! ```
//!
//! ## Numerical robustness
//!
//! `norm`, `normalize`, and `distance` handle vectors with very large (`1e30`)
//! or very small (`1e-30`) components: the calculation scales the values when
//! `x² + y² + …` would overflow or underflow to zero.

#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

use embedded_f32_sqrt::sqrt;

// ─────────────────────────────────────────────────────────────
//  Erreurs
// ─────────────────────────────────────────────────────────────

/// Errors returned by vector operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum VecError {
    /// Zero vector: normalization, projection, or reflection is undefined.
    ZeroNorm,
    /// A `NaN` or infinite value was found in the input or result.
    NonFiniteValue,
    /// Division by zero (scalar divisor or zero `w` component).
    DivisionByZero,
}

// ─────────────────────────────────────────────────────────────
//  Robust norm (internal)
// ─────────────────────────────────────────────────────────────

/// Euclidean norm without intermediate overflow or underflow.
fn robust_norm<const N: usize>(c: [f32; N]) -> Result<f32, VecError> {
    let mut max = 0.0_f32;
    for v in c {
        if !v.is_finite() {
            return Err(VecError::NonFiniteValue);
        }
        let a = v.abs();
        if a > max {
            max = a;
        }
    }
    if max == 0.0 {
        return Ok(0.0);
    }

    // Fast path: the sum of squares is representable and normal.
    let mut sq = 0.0_f32;
    for v in c {
        sq += v * v;
    }
    if sq.is_finite() && sq >= f32::MIN_POSITIVE {
        return sqrt(sq).map_err(|_| VecError::NonFiniteValue);
    }

    // Slow path: scale by the largest component.
    let mut s = 0.0_f32;
    for v in c {
        let r = v / max;
        s += r * r;
    }
    let n = sqrt(s).map_err(|_| VecError::NonFiniteValue)? * max;
    if n.is_finite() {
        Ok(n)
    } else {
        Err(VecError::NonFiniteValue)
    }
}

// ─────────────────────────────────────────────────────────────
//  Implementation shared by Vec2 / Vec3 / Vec4
// ─────────────────────────────────────────────────────────────

macro_rules! impl_vec {
    ($T:ident, $N:literal, $($f:ident : $i:literal),+) => {
        impl $T {
            /// Creates a new vector.
            #[inline]
            pub const fn new($($f: f32),+) -> Self {
                Self { $($f),+ }
            }

            /// Zero vector.
            pub const ZERO: Self = Self { $($f: 0.0),+ };

            /// Vector whose components are all `1.0`.
            pub const ONE: Self = Self { $($f: 1.0),+ };

            /// Returns the components as an array.
            #[inline]
            pub const fn as_array(&self) -> [f32; $N] {
                [$(self.$f),+]
            }

            /// Creates a vector from an array.
            #[inline]
            pub const fn from_array(v: [f32; $N]) -> Self {
                Self { $($f: v[$i]),+ }
            }

            /// Dot product.
            #[inline]
            pub fn dot(&self, rhs: &Self) -> f32 {
                0.0 $(+ self.$f * rhs.$f)+
            }

            /// Squared norm. Infallible, but may be `inf` or `0` for extreme
            /// components; use [`Self::norm`] in those cases.
            #[inline]
            pub fn norm_sq(&self) -> f32 {
                self.dot(self)
            }

            /// Euclidean norm (robust for very large or very small values).
            ///
            /// Returns [`VecError::NonFiniteValue`] if a component is `NaN` or
            /// infinite, or if the norm exceeds `f32::MAX`.
            /// The norm of the zero vector is `Ok(0.0)`.
            pub fn norm(&self) -> Result<f32, VecError> {
                robust_norm(self.as_array())
            }

            /// Unit vector in the same direction.
            ///
            /// Returns [`VecError::ZeroNorm`] for an exact zero vector and
            /// [`VecError::NonFiniteValue`] if a component is invalid.
            pub fn normalize(&self) -> Result<Self, VecError> {
                let n = self.norm()?;
                if n == 0.0 {
                    return Err(VecError::ZeroNorm);
                }
                Ok(Self { $($f: self.$f / n),+ })
            }

            /// Like [`Self::normalize`], but returns [`Self::ZERO`] on failure.
            #[inline]
            pub fn normalize_or_zero(&self) -> Self {
                self.normalize().unwrap_or(Self::ZERO)
            }

            /// Squared distance (avoids the square root).
            #[inline]
            pub fn distance_sq(&self, rhs: &Self) -> f32 {
                (*self - *rhs).norm_sq()
            }

            /// Distance euclidienne entre deux vecteurs.
            pub fn distance(&self, rhs: &Self) -> Result<f32, VecError> {
                (*self - *rhs).norm()
            }

            /// Linear interpolation: `self + t * (rhs - self)`.
            #[inline]
            pub fn lerp(&self, rhs: &Self, t: f32) -> Self {
                Self { $($f: self.$f + t * (rhs.$f - self.$f)),+ }
            }

            /// Component-wise multiplication (Hadamard product).
            #[inline]
            pub fn hadamard(&self, rhs: &Self) -> Self {
                Self { $($f: self.$f * rhs.$f),+ }
            }

            /// Component-wise minimum.
            #[inline]
            pub fn min(&self, rhs: &Self) -> Self {
                Self { $($f: self.$f.min(rhs.$f)),+ }
            }

            /// Component-wise maximum.
            #[inline]
            pub fn max(&self, rhs: &Self) -> Self {
                Self { $($f: self.$f.max(rhs.$f)),+ }
            }

            /// Component-wise absolute value.
            #[inline]
            pub fn abs(&self) -> Self {
                Self { $($f: self.$f.abs()),+ }
            }

            /// Divides by a scalar without silently producing `inf` or `NaN`.
            ///
            /// Returns [`VecError::DivisionByZero`] if `s == 0.0` and
            /// [`VecError::NonFiniteValue`] if the result is not finite.
            pub fn checked_div(&self, s: f32) -> Result<Self, VecError> {
                if s == 0.0 {
                    return Err(VecError::DivisionByZero);
                }
                let r = *self / s;
                if r.is_finite() { Ok(r) } else { Err(VecError::NonFiniteValue) }
            }

            /// Projection de `self` sur `rhs` : `(self·rhs / |rhs|²) * rhs`.
            ///
            /// Scale-independent for both inputs, avoiding overflow in intermediate
            /// dot products and squared norms. Returns [`VecError::ZeroNorm`] if
            /// `rhs` is zero, or [`VecError::NonFiniteValue`] for non-finite inputs
            /// or an unrepresentable result.
            pub fn project_onto(&self, rhs: &Self) -> Result<Self, VecError> {
                let mut rhs_scale = 0.0_f32;
                for v in rhs.as_array() {
                    if !v.is_finite() {
                        return Err(VecError::NonFiniteValue);
                    }
                    let a = v.abs();
                    if a > rhs_scale {
                        rhs_scale = a;
                    }
                }
                if rhs_scale == 0.0 {
                    return Err(VecError::ZeroNorm);
                }

                let mut self_scale = 0.0_f32;
                for v in self.as_array() {
                    if !v.is_finite() {
                        return Err(VecError::NonFiniteValue);
                    }
                    let a = v.abs();
                    if a > self_scale {
                        self_scale = a;
                    }
                }
                if self_scale == 0.0 {
                    return Ok(Self::ZERO);
                }

                let direction = *rhs / rhs_scale;
                let scaled_self = *self / self_scale;
                let factor = scaled_self.dot(&direction) / direction.norm_sq();
                let out = (direction * factor) * self_scale;
                if out.is_finite() { Ok(out) } else { Err(VecError::NonFiniteValue) }
            }

            /// Component of `self` perpendicular to `rhs`: `self - proj(self, rhs)`.
            pub fn reject_from(&self, rhs: &Self) -> Result<Self, VecError> {
                let out = *self - self.project_onto(rhs)?;
                if out.is_finite() { Ok(out) } else { Err(VecError::NonFiniteValue) }
            }

            /// Reflects `self` across the plane or line with normal `normal`.
            ///
            /// `normal` does not need to be a unit vector, but must be nonzero.
            pub fn reflect(&self, normal: &Self) -> Result<Self, VecError> {
                let out = *self - self.project_onto(normal)? * 2.0;
                if out.is_finite() { Ok(out) } else { Err(VecError::NonFiniteValue) }
            }

            /// Returns `true` if all components are finite.
            #[inline]
            pub fn is_finite(&self) -> bool {
                true $(&& self.$f.is_finite())+
            }

            /// Approximate equality: each component differs by at most `eps`.
            #[inline]
            pub fn is_approx_eq(&self, rhs: &Self, eps: f32) -> bool {
                true $(&& (self.$f - rhs.$f).abs() <= eps)+
            }
        }

        impl Default for $T {
            #[inline]
            fn default() -> Self { Self::ZERO }
        }
        impl From<[f32; $N]> for $T {
            #[inline]
            fn from(v: [f32; $N]) -> Self { Self::from_array(v) }
        }
        impl From<$T> for [f32; $N] {
            #[inline]
            fn from(v: $T) -> Self { v.as_array() }
        }
        impl core::ops::Add for $T {
            type Output = Self;
            #[inline]
            fn add(self, rhs: Self) -> Self { Self { $($f: self.$f + rhs.$f),+ } }
        }
        impl core::ops::Sub for $T {
            type Output = Self;
            #[inline]
            fn sub(self, rhs: Self) -> Self { Self { $($f: self.$f - rhs.$f),+ } }
        }
        impl core::ops::Mul<f32> for $T {
            type Output = Self;
            #[inline]
            fn mul(self, s: f32) -> Self { Self { $($f: self.$f * s),+ } }
        }
        impl core::ops::Mul<$T> for f32 {
            type Output = $T;
            #[inline]
            fn mul(self, v: $T) -> $T { v * self }
        }
        impl core::ops::Div<f32> for $T {
            type Output = Self;
            #[inline]
            fn div(self, s: f32) -> Self { Self { $($f: self.$f / s),+ } }
        }
        impl core::ops::Neg for $T {
            type Output = Self;
            #[inline]
            fn neg(self) -> Self { Self { $($f: -self.$f),+ } }
        }
        impl core::ops::AddAssign for $T {
            #[inline]
            fn add_assign(&mut self, rhs: Self) { $(self.$f += rhs.$f;)+ }
        }
        impl core::ops::SubAssign for $T {
            #[inline]
            fn sub_assign(&mut self, rhs: Self) { $(self.$f -= rhs.$f;)+ }
        }
        impl core::ops::MulAssign<f32> for $T {
            #[inline]
            fn mul_assign(&mut self, s: f32) { $(self.$f *= s;)+ }
        }
        impl core::ops::DivAssign<f32> for $T {
            #[inline]
            fn div_assign(&mut self, s: f32) { $(self.$f /= s;)+ }
        }
        impl core::iter::Sum for $T {
            fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
                iter.fold(Self::ZERO, |a, b| a + b)
            }
        }
    };
}

// ─────────────────────────────────────────────────────────────
//  Vec2
// ─────────────────────────────────────────────────────────────

/// A 2D vector of `f32` components.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec2 {
    /// X component.
    pub x: f32,
    /// Y component.
    pub y: f32,
}

impl_vec!(Vec2, 2, x: 0, y: 1);

impl Vec2 {
    /// Unit vector along X: `[1, 0]`.
    pub const X: Self = Self::new(1.0, 0.0);
    /// Unit vector along Y: `[0, 1]`.
    pub const Y: Self = Self::new(0.0, 1.0);

    /// 2D cross product (the Z component of `self × rhs`): `x₁y₂ - y₁x₂`.
    ///
    /// Positive when `rhs` is to the left of `self` (counterclockwise).
    #[inline]
    pub fn cross(&self, rhs: &Self) -> f32 {
        self.x * rhs.y - self.y * rhs.x
    }

    /// Perpendicular vector (90° counterclockwise rotation): `[-y, x]`.
    #[inline]
    pub const fn perp(&self) -> Self {
        Self::new(-self.y, self.x)
    }

    /// Extends to `Vec3` with the `z` component.
    #[inline]
    pub const fn extend(&self, z: f32) -> Vec3 {
        Vec3::new(self.x, self.y, z)
    }
}

// ─────────────────────────────────────────────────────────────
//  Vec3
// ─────────────────────────────────────────────────────────────

/// A 3D vector of `f32` components.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec3 {
    /// X component.
    pub x: f32,
    /// Y component.
    pub y: f32,
    /// Z component.
    pub z: f32,
}

impl_vec!(Vec3, 3, x: 0, y: 1, z: 2);

impl Vec3 {
    /// Unit vector along X: `[1, 0, 0]`.
    pub const X: Self = Self::new(1.0, 0.0, 0.0);
    /// Unit vector along Y: `[0, 1, 0]`.
    pub const Y: Self = Self::new(0.0, 1.0, 0.0);
    /// Unit vector along Z: `[0, 0, 1]`.
    pub const Z: Self = Self::new(0.0, 0.0, 1.0);

    /// Cross product: `self × rhs` (right-hand rule).
    ///
    /// Property: `a × b = -(b × a)`.
    #[inline]
    pub fn cross(&self, rhs: &Self) -> Self {
        Self::new(
            self.y * rhs.z - self.z * rhs.y,
            self.z * rhs.x - self.x * rhs.z,
            self.x * rhs.y - self.y * rhs.x,
        )
    }

    /// Scalar triple product: `self · (b × c)` (signed parallelepiped volume).
    #[inline]
    pub fn triple(&self, b: &Self, c: &Self) -> f32 {
        self.dot(&b.cross(c))
    }

    /// Removes the `z` component.
    #[inline]
    pub const fn truncate(&self) -> Vec2 {
        Vec2::new(self.x, self.y)
    }

    /// Extends to `Vec4` with the `w` component.
    #[inline]
    pub const fn extend(&self, w: f32) -> Vec4 {
        Vec4::new(self.x, self.y, self.z, w)
    }
}

// ─────────────────────────────────────────────────────────────
//  Vec4
// ─────────────────────────────────────────────────────────────

/// A 4D vector of `f32` components.
///
/// Useful for homogeneous coordinates (`w=1` for a point, `w=0` for a
/// direction), RGBA colors, and quaternions `(x, y, z, w)`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec4 {
    /// X component.
    pub x: f32,
    /// Y component.
    pub y: f32,
    /// Z component.
    pub z: f32,
    /// W component.
    pub w: f32,
}

impl_vec!(Vec4, 4, x: 0, y: 1, z: 2, w: 3);

impl Vec4 {
    /// Unit vector along X: `[1, 0, 0, 0]`.
    pub const X: Self = Self::new(1.0, 0.0, 0.0, 0.0);
    /// Unit vector along Y: `[0, 1, 0, 0]`.
    pub const Y: Self = Self::new(0.0, 1.0, 0.0, 0.0);
    /// Unit vector along Z: `[0, 0, 1, 0]`.
    pub const Z: Self = Self::new(0.0, 0.0, 1.0, 0.0);
    /// Unit vector along W: `[0, 0, 0, 1]`.
    pub const W: Self = Self::new(0.0, 0.0, 0.0, 1.0);

    /// Creates a `Vec4` from a `Vec3` by adding `w`.
    ///
    /// Convention: `w=1.0` for a point and `w=0.0` for a direction.
    #[inline]
    pub const fn from_vec3(v: Vec3, w: f32) -> Self {
        Self::new(v.x, v.y, v.z, w)
    }

    /// Extracts the XYZ components as a `Vec3`, ignoring `w`.
    #[inline]
    pub const fn xyz(&self) -> Vec3 {
        Vec3::new(self.x, self.y, self.z)
    }

    /// Perspective divide: `(x/w, y/w, z/w)`.
    ///
    /// Returns [`VecError::DivisionByZero`] if `w == 0` (a direction or point
    /// at infinity), and [`VecError::NonFiniteValue`] if the result is not finite.
    pub fn perspective_divide(&self) -> Result<Vec3, VecError> {
        self.xyz().checked_div(self.w)
    }
}