Skip to main content

embedded_dsp/
types.rs

1//! Data types, status codes, complex structures, and fixed-point helper types.
2
3#[allow(non_camel_case_types)]
4pub type q7 = i8;
5#[allow(non_camel_case_types)]
6pub type q15 = i16;
7#[allow(non_camel_case_types)]
8pub type q31 = i32;
9#[allow(non_camel_case_types)]
10pub type q63 = i64;
11#[allow(non_camel_case_types)]
12pub type f32_t = f32;
13#[allow(non_camel_case_types)]
14pub type f64_t = f64;
15
16/// Error status returned by functions in `embedded-dsp`.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[repr(i8)]
19pub enum Status {
20    /// Operation succeeded without error.
21    Success = 0,
22    /// One or more arguments are invalid.
23    ArgumentError = -1,
24    /// Length of data buffer is invalid or mismatching.
25    LengthError = -2,
26    /// Matrix dimensions are incompatible.
27    SizeMismatch = -3,
28    /// NaN or Infinity was produced during computation.
29    NanInf = -4,
30    /// Matrix is singular and cannot be inverted.
31    Singular = -5,
32    /// Test or verification failed.
33    TestFailure = -6,
34    /// Matrix decomposition failed.
35    DecompositionFailure = -7,
36}
37
38/// Representation of a complex number with real and imaginary components.
39#[derive(Debug, Clone, Copy, PartialEq, Default)]
40#[repr(C)]
41pub struct Complex<T> {
42    pub real: T,
43    pub imag: T,
44}
45
46impl<T> Complex<T> {
47    #[inline(always)]
48    pub const fn new(real: T, imag: T) -> Self {
49        Self { real, imag }
50    }
51}
52
53/// Helper function for saturating multiplication in Q15 format.
54#[inline(always)]
55pub fn q15_mult(a: q15, b: q15) -> q15 {
56    let mul = (a as i32 * b as i32) >> 15;
57    mul.clamp(i16::MIN as i32, i16::MAX as i32) as i16
58}
59
60/// Helper function for saturating multiplication in Q31 format.
61#[inline(always)]
62pub fn q31_mult(a: q31, b: q31) -> q31 {
63    let mul = (a as i64 * b as i64) >> 31;
64    mul.clamp(i32::MIN as i64, i32::MAX as i64) as i32
65}
66
67/// Helper function for saturating multiplication in Q7 format.
68#[inline(always)]
69pub fn q7_mult(a: q7, b: q7) -> q7 {
70    let mul = (a as i32 * b as i32) >> 7;
71    mul.clamp(i8::MIN as i32, i8::MAX as i32) as i8
72}