scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
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
//! Embedded Systems Support for SciRS2 (v0.2.0)
//!
//! This module provides no_std-compatible utilities and abstractions for embedded systems,
//! including ARM Cortex-M, RISC-V, AVR, and embedded Linux targets.
//!
//! # Features
//!
//! - **no_std Compatible**: Works without standard library
//! - **Fixed-Point Arithmetic**: For systems without FPU
//! - **Stack-Based Operations**: Minimal heap usage
//! - **Deterministic Execution**: Predictable timing for real-time systems
//! - **Memory-Constrained**: Optimized for limited RAM/ROM
//!
//! # Example: Basic Embedded Usage
//!
//! ```rust,ignore
//! #![no_std]
//! #![no_main]
//!
//! use scirs2_core::embedded::*;
//!
//! #[entry]
//! fn main() -> ! {
//!     // Fixed-size array operations (no heap allocation)
//!     let data = StackArray::<f32, 16>::new();
//!
//!     // Deterministic computation
//!     let result = stack_based_filter(&data);
//!
//!     loop {}
//! }
//! ```
//!
//! # Memory Requirements
//!
//! - **Minimum RAM**: 8KB (basic operations)
//! - **Recommended RAM**: 32KB (full functionality)
//! - **Flash/ROM**: 64KB (core functionality)
//!
//! # Supported Platforms
//!
//! - ARM Cortex-M (M0/M0+/M3/M4/M7/M33)
//! - RISC-V (RV32I/RV32IMC/RV32IMAC)
//! - AVR (ATmega series)
//! - Embedded Linux (no libc)

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(all(feature = "alloc", not(feature = "std")))]
extern crate alloc;

#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::vec::Vec;

use crate::error::{CoreError, CoreResult};
use core::marker::PhantomData;
use num_traits::{Float, NumAssignOps, Zero};

// Re-exports for convenience
pub use error_handling::{EmbeddedError, EmbeddedResult};
pub use memory_estimation::{estimate_stack_usage, MemoryRequirement};
pub use stack_array::{BufferFullError, FixedSizeBuffer, StackArray};

/// Stack-based computation for element-wise operations
///
/// Performs operations without heap allocation, suitable for embedded systems.
///
/// # Example
///
/// ```rust
/// use scirs2_core::embedded::StackArray;
///
/// let a = StackArray::<f32, 8>::new();
/// let b = StackArray::<f32, 8>::new();
/// // Perform element-wise operations
/// ```
#[inline]
pub fn stack_add<T, const N: usize>(a: &StackArray<T, N>, b: &StackArray<T, N>) -> StackArray<T, N>
where
    T: Float + NumAssignOps + Copy + Default,
{
    let mut result = StackArray::new();
    for i in 0..N {
        result.data[i] = a.data[i] + b.data[i];
    }
    result
}

/// Stack-based multiplication
#[inline]
pub fn stack_mul<T, const N: usize>(a: &StackArray<T, N>, b: &StackArray<T, N>) -> StackArray<T, N>
where
    T: Float + NumAssignOps + Copy + Default,
{
    let mut result = StackArray::new();
    for i in 0..N {
        result.data[i] = a.data[i] * b.data[i];
    }
    result
}

/// Calculate sum without heap allocation
#[inline]
pub fn stack_sum<T, const N: usize>(arr: &StackArray<T, N>) -> T
where
    T: Float + NumAssignOps + Copy + Default + Zero,
{
    let mut sum = T::zero();
    for i in 0..N {
        sum += arr.data[i];
    }
    sum
}

/// Calculate mean without heap allocation
#[inline]
pub fn stack_mean<T, const N: usize>(arr: &StackArray<T, N>) -> T
where
    T: Float + NumAssignOps + Copy + Default + Zero,
{
    if N == 0 {
        return T::zero();
    }
    stack_sum(arr) / T::from(N).expect("Failed to convert N to T")
}

/// Memory estimation utilities
pub mod memory_estimation {
    use core::mem;

    /// Estimated memory requirement for an operation
    #[derive(Debug, Copy, Clone)]
    pub struct MemoryRequirement {
        /// Stack memory in bytes
        pub stack_bytes: usize,
        /// Heap memory in bytes (if alloc feature enabled)
        pub heap_bytes: usize,
        /// ROM/Flash memory in bytes
        pub flash_bytes: usize,
    }

    impl MemoryRequirement {
        /// Create a new memory requirement estimate
        pub const fn new(stack_bytes: usize, heap_bytes: usize, flash_bytes: usize) -> Self {
            Self {
                stack_bytes,
                heap_bytes,
                flash_bytes,
            }
        }

        /// Estimate for basic operations
        pub const fn basic() -> Self {
            Self::new(1024, 0, 4096)
        }

        /// Estimate for signal processing
        pub const fn signal_processing() -> Self {
            Self::new(4096, 0, 16384)
        }

        /// Estimate for linear algebra
        pub const fn linalg() -> Self {
            Self::new(8192, 0, 32768)
        }
    }

    /// Estimate stack usage for a given array size
    pub const fn estimate_stack_usage<T>(count: usize) -> usize {
        mem::size_of::<T>() * count
    }
}

/// Error handling for embedded systems
pub mod error_handling {
    use core::fmt;

    /// Embedded-specific error types (no heap allocation)
    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    pub enum EmbeddedError {
        /// Buffer overflow
        BufferOverflow,
        /// Buffer underflow
        BufferUnderflow,
        /// Invalid size
        InvalidSize,
        /// Out of memory
        OutOfMemory,
        /// Numerical error
        NumericalError,
        /// Not supported in no_std mode
        NotSupported,
    }

    impl fmt::Display for EmbeddedError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                EmbeddedError::BufferOverflow => write!(f, "Buffer overflow"),
                EmbeddedError::BufferUnderflow => write!(f, "Buffer underflow"),
                EmbeddedError::InvalidSize => write!(f, "Invalid size"),
                EmbeddedError::OutOfMemory => write!(f, "Out of memory"),
                EmbeddedError::NumericalError => write!(f, "Numerical error"),
                EmbeddedError::NotSupported => write!(f, "Not supported in no_std mode"),
            }
        }
    }

    /// Result type for embedded operations
    pub type EmbeddedResult<T> = Result<T, EmbeddedError>;
}

/// Stack array module
pub mod stack_array {
    use core::marker::PhantomData;

    /// Error returned when attempting to push to a full buffer
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct BufferFullError;

    impl core::fmt::Display for BufferFullError {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            write!(f, "buffer is full")
        }
    }

    /// Stack-based array for no-heap operations
    ///
    /// This provides a fixed-size array allocated on the stack,
    /// suitable for embedded systems without heap allocation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use scirs2_core::embedded::StackArray;
    ///
    /// let mut data = StackArray::<f32, 16>::new();
    /// data[0] = 1.0;
    /// data[1] = 2.0;
    /// assert_eq!(data.len(), 16);
    /// ```
    #[derive(Debug, Clone)]
    pub struct StackArray<T, const N: usize> {
        pub(super) data: [T; N],
        _marker: PhantomData<T>,
    }

    impl<T: Copy + Default, const N: usize> StackArray<T, N> {
        /// Create a new stack-allocated array initialized with default values
        #[inline]
        pub fn new() -> Self {
            Self {
                data: [T::default(); N],
                _marker: PhantomData,
            }
        }

        /// Create from a slice (copies data if it fits)
        #[inline]
        pub fn from_slice(slice: &[T]) -> Option<Self> {
            if slice.len() != N {
                return None;
            }
            let mut result = Self::new();
            result.data.copy_from_slice(slice);
            Some(result)
        }

        /// Get the length of the array
        #[inline]
        pub const fn len(&self) -> usize {
            N
        }

        /// Check if the array is empty (always false for const generic arrays)
        #[inline]
        pub const fn is_empty(&self) -> bool {
            N == 0
        }

        /// Get a reference to the underlying array
        #[inline]
        pub fn as_slice(&self) -> &[T] {
            &self.data
        }

        /// Get a mutable reference to the underlying array
        #[inline]
        pub fn as_mut_slice(&mut self) -> &mut [T] {
            &mut self.data
        }
    }

    impl<T: Copy + Default, const N: usize> Default for StackArray<T, N> {
        fn default() -> Self {
            Self::new()
        }
    }

    impl<T, const N: usize> core::ops::Index<usize> for StackArray<T, N> {
        type Output = T;

        #[inline]
        fn index(&self, index: usize) -> &Self::Output {
            &self.data[index]
        }
    }

    impl<T, const N: usize> core::ops::IndexMut<usize> for StackArray<T, N> {
        #[inline]
        fn index_mut(&mut self, index: usize) -> &mut Self::Output {
            &mut self.data[index]
        }
    }

    /// Fixed-size buffer for streaming operations
    ///
    /// Useful for real-time signal processing where data arrives continuously.
    ///
    /// # Example
    ///
    /// ```rust
    /// use scirs2_core::embedded::FixedSizeBuffer;
    ///
    /// let mut buffer = FixedSizeBuffer::<f32, 8>::new();
    /// buffer.push(1.0).expect("Buffer should not be full");
    /// buffer.push(2.0).expect("Buffer should not be full");
    /// assert_eq!(buffer.len(), 2);
    /// ```
    #[derive(Debug, Clone)]
    pub struct FixedSizeBuffer<T, const N: usize> {
        pub(super) data: [T; N],
        len: usize,
        _marker: PhantomData<T>,
    }

    impl<T: Copy + Default, const N: usize> FixedSizeBuffer<T, N> {
        /// Create a new empty buffer
        #[inline]
        pub fn new() -> Self {
            Self {
                data: [T::default(); N],
                len: 0,
                _marker: PhantomData,
            }
        }

        /// Push an element to the buffer (returns error if full)
        #[inline]
        pub fn push(&mut self, value: T) -> Result<(), BufferFullError> {
            if self.len >= N {
                return Err(BufferFullError);
            }
            self.data[self.len] = value;
            self.len += 1;
            Ok(())
        }

        /// Pop an element from the buffer (returns None if empty)
        #[inline]
        pub fn pop(&mut self) -> Option<T> {
            if self.len == 0 {
                return None;
            }
            self.len -= 1;
            Some(self.data[self.len])
        }

        /// Get the current length
        #[inline]
        pub const fn len(&self) -> usize {
            self.len
        }

        /// Check if the buffer is empty
        #[inline]
        pub const fn is_empty(&self) -> bool {
            self.len == 0
        }

        /// Check if the buffer is full
        #[inline]
        pub const fn is_full(&self) -> bool {
            self.len == N
        }

        /// Get the capacity
        #[inline]
        pub const fn capacity(&self) -> usize {
            N
        }

        /// Clear the buffer
        #[inline]
        pub fn clear(&mut self) {
            self.len = 0;
        }

        /// Get a slice of the valid data
        #[inline]
        pub fn as_slice(&self) -> &[T] {
            &self.data[..self.len]
        }
    }

    impl<T: Copy + Default, const N: usize> Default for FixedSizeBuffer<T, N> {
        fn default() -> Self {
            Self::new()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_stack_array_basic() {
        let mut arr = StackArray::<f32, 8>::new();
        arr[0] = 1.0;
        arr[1] = 2.0;
        assert_eq!(arr.len(), 8);
        assert_eq!(arr[0], 1.0);
        assert_eq!(arr[1], 2.0);
    }

    #[test]
    fn test_fixed_size_buffer() {
        let mut buffer = FixedSizeBuffer::<f32, 4>::new();
        assert!(buffer.is_empty());

        buffer.push(1.0).expect("Failed to push");
        buffer.push(2.0).expect("Failed to push");
        assert_eq!(buffer.len(), 2);

        assert_eq!(buffer.pop(), Some(2.0));
        assert_eq!(buffer.len(), 1);
    }

    #[test]
    fn test_stack_operations() {
        let mut a = StackArray::<f32, 4>::new();
        let mut b = StackArray::<f32, 4>::new();

        for i in 0..4 {
            a[i] = i as f32;
            b[i] = (i + 1) as f32;
        }

        let sum = stack_add(&a, &b);
        assert_eq!(sum[0], 1.0);
        assert_eq!(sum[1], 3.0);

        let product = stack_mul(&a, &b);
        assert_eq!(product[0], 0.0);
        assert_eq!(product[1], 2.0);
    }

    #[test]
    fn test_stack_statistics() {
        let mut arr = StackArray::<f32, 4>::new();
        arr[0] = 1.0;
        arr[1] = 2.0;
        arr[2] = 3.0;
        arr[3] = 4.0;

        let total = stack_sum(&arr);
        assert_eq!(total, 10.0);

        let avg = stack_mean(&arr);
        assert_eq!(avg, 2.5);
    }
}