lasprs 0.14.1

Library for Acoustic Signal Processing (Rust edition, with optional Python bindings via pyo3)
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
//! Newtype wrappers for type-safe numeric values.
//!
//! This module provides several newtype wrappers that enforce constraints on numeric values
//! at compile time and runtime:
//!
//! - [`Positive`]: A value that must be strictly greater than zero
//! - [`Bounded`]: A positive value within inclusive bounds (min ≤ value ≤ max)
//! - [`StrictBounded`]: A positive value within exclusive bounds (min < value < max)
//!
//! All types use generic const parameters for compile-time bounds checking where applicable,
//! ensuring type safety and zero runtime overhead for bound storage.
//!
//! # Examples
//!
/// ```
/// use lasprs::{Positive, Bounded, StrictBounded};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Simple positive value
/// let positive = Positive::new(5.0)?;
///
/// // Bounded with inclusive bounds [1.0, 10.0]
/// type SmallRange = Bounded<1, 10>;
/// let bounded = SmallRange::new(5.0)?; // OK
/// let bounded = SmallRange::new(1.0)?; // OK (inclusive)
/// let bounded = SmallRange::new(10.0)?; // OK (inclusive)
///
/// // Strictly bounded with exclusive bounds (1.0, 10.0)
/// type StrictRange = StrictBounded<1, 10>;
/// let strict = StrictRange::new(5.0)?; // OK
/// // let strict = StrictRange::new(1.0)?; // Error (exclusive)
/// // let strict = StrictRange::new(10.0)?; // Error (exclusive)
/// # Ok(())
/// # }
/// ```
use crate::config::*;
use serde::{Deserialize, Serialize};
use snafu::prelude::*;
use std::ops::Deref;

type Result<T> = std::result::Result<T, ValidationError>;

#[allow(missing_docs)]
#[cfg_attr(
    feature = "python-bindings",
    gen_stub_pyclass_complex_enum,
    pyclass(from_py_object)
)]
#[derive(Snafu, Debug, Clone, Copy, PartialEq)]
pub enum ValidationError {
    #[snafu(display("Value {} is out of range. Should be within ({}, {})", value, min, max))]
    ExclusiveValueOutOfRange { value: f64, min: f64, max: f64 },

    #[snafu(display("Value {} is out of range. Should be within [{}, {}]", value, min, max))]
    InclusiveValueOutOfRange { value: f64, min: f64, max: f64 },
}

#[cfg(feature = "python-bindings")]
impl From<ValidationError> for PyErr {
    fn from(value: ValidationError) -> Self {
        PyErr::new::<ValidationError, _>(value)
    }
}

/// A newtype wrapper for positive floating point values.
///
/// This type ensures that the wrapped value is strictly greater than zero.
/// It provides transparent access to the underlying value through [`Deref`].
///
/// # Examples
///
/// ```
/// use lasprs::Positive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let pos = Positive::new(5.0)?;
/// assert_eq!(*pos, 5.0);
///
/// // This would fail:
/// // let invalid = Positive::new(-1.0)?; // Error: Value must be positive
/// # Ok(())
/// # }
/// ```
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, derive_more::Display)]
#[cfg_attr(feature = "python-bindings", gen_stub_pyclass, pyclass(from_py_object))]
pub struct Positive(Flt);

impl Positive {
    /// Create a new positive floating point value.
    pub fn new(value: Flt) -> Result<Self> {
        ensure!(
            value >= 0.0,
            InclusiveValueOutOfRangeSnafu {
                min: 0.0,
                max: FltInf,
                value
            }
        );
        Ok(Self(value))
    }
}

#[cfg(feature = "python-bindings")]
#[cfg_attr(feature = "python-bindings", gen_stub_pymethods, pymethods)]
impl Positive {
    /// Get the value of the positive floating point value.
    #[allow(dead_code)]
    fn toFloat(&self) -> Flt {
        self.0
    }
    #[new]
    fn py_new(value: Flt) -> PyResult<Self> {
        Ok(Self::new(value)?)
    }
}

impl TryFrom<Flt> for Positive {
    type Error = ValidationError;

    fn try_from(value: Flt) -> Result<Self> {
        Self::new(value)
    }
}
impl Deref for Positive {
    type Target = Flt;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
/// Strictly positive floating point value.
#[cfg_attr(feature = "python-bindings", gen_stub_pyclass, pyclass(from_py_object))]
#[derive(Copy, Clone, Debug, PartialEq, derive_more::Display, Serialize, Deserialize)]
pub struct StrictlyPositive(Flt);

impl StrictlyPositive {
    /// Create a new positive floating point value.
    pub fn new(value: Flt) -> Result<Self> {
        ensure!(
            value > 0.0,
            ExclusiveValueOutOfRangeSnafu {
                min: 0.0,
                max: FltInf,
                value
            }
        );
        Ok(Self(value))
    }
    /// Create a new positive floating point value of 1.0.
    pub fn one() -> Self {
        Self(1.0)
    }
}
#[cfg_attr(feature = "python-bindings", gen_stub_pymethods, pymethods)]
impl StrictlyPositive {
    /// Create a new positive floating point value.
    #[allow(dead_code)]
    fn toFloat(&self) -> Flt {
        self.0
    }
    #[cfg(feature = "python-bindings")]
    #[new]
    fn new_py(val: Flt) -> PyResult<Self> {
        Ok(Self::new(val)?)
    }
}

impl TryFrom<Flt> for StrictlyPositive {
    type Error = ValidationError;

    fn try_from(value: Flt) -> Result<Self> {
        Self::new(value)
    }
}
impl Deref for StrictlyPositive {
    type Target = Flt;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// A newtype wrapper for positive floating point values within inclusive bounds.
///
/// This type ensures that the wrapped value is positive and falls within the specified
/// bounds (inclusive). The bounds are specified as generic const parameters, making
/// each combination of bounds a distinct type.
///
/// # Type Parameters
///
/// - `MIN`: The minimum allowed value (inclusive, must be positive)
/// - `MAX`: The maximum allowed value (inclusive, must be positive and > MIN)
///
/// # Examples
///
/// ```
/// use lasprs::Bounded;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// type Percentage = Bounded<0, 100>;  // Values between 0.0 and 100.0
/// type SmallRange = Bounded<1, 10>;   // Values between 1.0 and 10.0
///
/// let percent = Percentage::new(50.0)?;  // OK
/// let percent = Percentage::new(0.0)?;   // OK (inclusive)
/// let percent = Percentage::new(100.0)?; // OK (inclusive)
///
/// let small = SmallRange::new(5.0)?;     // OK
/// let small = SmallRange::new(1.0)?;     // OK (inclusive)
/// let small = SmallRange::new(10.0)?;    // OK (inclusive)
///
/// // These are different types:
/// // let invalid: Percentage = small;    // Compile error!
/// # Ok(())
/// # }
/// ```
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
pub struct Bounded<const MIN: i32, const MAX: i32>(Flt);

/// Value between 0.0 and 100.0, denoting a percentage
pub type Percentage = Bounded<0, 100>;

impl<const MIN: i32, const MAX: i32> Bounded<MIN, MAX> {
    /// Create a new bounded positive floating point value.
    /// The value must be positive and within the specified bounds (inclusive).
    pub fn new(value: Flt) -> Result<Self> {
        let min = MIN as Flt;
        let max = MAX as Flt;
        debug_assert!(min < max);
        ensure!(
            value >= min,
            InclusiveValueOutOfRangeSnafu { min, max, value }
        );
        ensure!(
            value <= max,
            InclusiveValueOutOfRangeSnafu { min, max, value }
        );

        Ok(Self(value))
    }
}

impl<const MIN: i32, const MAX: i32> TryFrom<Flt> for Bounded<MIN, MAX> {
    type Error = ValidationError;

    fn try_from(value: Flt) -> Result<Self> {
        Self::new(value)
    }
}

impl<const MIN: i32, const MAX: i32> Deref for Bounded<MIN, MAX> {
    type Target = Flt;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

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

    #[test]
    fn test_positive_valid() {
        let pos = Positive::new(5.0).unwrap();
        assert_eq!(*pos, 5.0);

        let pos = Positive::new(0.1).unwrap();
        assert_eq!(*pos, 0.1);

        let pos = Positive::new(1000.0).unwrap();
        assert_eq!(*pos, 1000.0);
    }

    #[test]
    fn test_positive_invalid() {
        assert!(Positive::new(-1e-300).is_err());
        assert!(Positive::new(-1.0).is_err());
        assert!(Positive::new(Flt::NAN).is_err());
    }

    #[test]
    fn test_positive_try_from() {
        let pos: Result<Positive> = 5.0.try_into();
        assert!(pos.is_ok());
        assert_eq!(*pos.unwrap(), 5.0);

        let pos: Result<Positive> = (-1.0).try_into();
        assert!(pos.is_err());
    }

    #[test]
    fn test_bounded_valid() {
        type TestBounded = Bounded<1, 10>;

        let bounded = TestBounded::new(5.0).unwrap();
        assert_eq!(*bounded, 5.0);

        // Test inclusive bounds
        let bounded = TestBounded::new(1.0).unwrap();
        assert_eq!(*bounded, 1.0);

        let bounded = TestBounded::new(10.0).unwrap();
        assert_eq!(*bounded, 10.0);
    }

    #[test]
    fn test_bounded_invalid() {
        type TestBounded = Bounded<1, 10>;

        // Value too small
        assert!(TestBounded::new(0.9).is_err());

        // Value too large
        assert!(TestBounded::new(10.1).is_err());

        // Negative value
        assert!(TestBounded::new(-1.0).is_err());

        // Zero
        assert!(TestBounded::new(0.0).is_err());
    }

    #[test]
    fn test_strictlybounded_invalid_bounds() {
        // These should fail at runtime when trying to create values
        type InvalidBounds1 = StrictBounded<0, 10>; // MIN is not positive
        type InvalidBounds2 = StrictBounded<8, 10>; // MIN >= MAX

        assert!(InvalidBounds1::new(10.0).is_err());
        assert!(InvalidBounds2::new(7.0).is_err());
    }

    #[test]
    fn test_bounded_try_from() {
        type TestBounded = Bounded<1, 10>;

        let bounded: Result<TestBounded> = 5.0.try_into();
        assert!(bounded.is_ok());
        assert_eq!(*bounded.unwrap(), 5.0);

        let bounded: Result<TestBounded> = 15.0.try_into();
        assert!(bounded.is_err());
    }

    #[test]
    fn test_strict_bounded_valid() {
        type TestStrictBounded = StrictBounded<1, 10>;

        let strict = TestStrictBounded::new(5.0).unwrap();
        assert_eq!(*strict, 5.0);

        // Test values just inside bounds
        let strict = TestStrictBounded::new(1.1).unwrap();
        assert_eq!(*strict, 1.1);

        let strict = TestStrictBounded::new(9.9).unwrap();
        assert_eq!(*strict, 9.9);
    }

    #[test]
    fn test_strict_bounded_invalid() {
        type TestStrictBounded = StrictBounded<1, 10>;

        // Values at bounds (should be rejected for exclusive bounds)
        assert!(TestStrictBounded::new(1.0).is_err());
        assert!(TestStrictBounded::new(10.0).is_err());

        // Value too small
        assert!(TestStrictBounded::new(0.9).is_err());

        // Value too large
        assert!(TestStrictBounded::new(10.1).is_err());

        // Negative value
        assert!(TestStrictBounded::new(-1.0).is_err());

        // Zero
        assert!(TestStrictBounded::new(0.0).is_err());
    }

    #[test]
    fn test_strict_bounded_try_from() {
        type TestStrictBounded = StrictBounded<1, 10>;

        let strict: Result<TestStrictBounded> = 5.0.try_into();
        assert!(strict.is_ok());
        assert_eq!(*strict.unwrap(), 5.0);

        let strict: Result<TestStrictBounded> = 1.0.try_into();
        assert!(strict.is_err());

        let strict: Result<TestStrictBounded> = 10.0.try_into();
        assert!(strict.is_err());
    }

    #[test]
    fn test_different_bounded_types() {
        type SmallBounded = Bounded<1, 10>;
        type LargeBounded = Bounded<100, 1000>;

        let small = SmallBounded::new(5.0).unwrap();
        let large = LargeBounded::new(500.0).unwrap();

        assert_eq!(*small, 5.0);
        assert_eq!(*large, 500.0);
    }

    #[test]
    fn test_serde_serialization() {
        use serde_json;

        let pos = Positive::new(5.0).unwrap();
        let serialized = serde_json::to_string(&pos).unwrap();
        let deserialized: Positive = serde_json::from_str(&serialized).unwrap();
        assert_eq!(*pos, *deserialized);

        type TestBounded = Bounded<1, 10>;
        let bounded = TestBounded::new(5.0).unwrap();
        let serialized = serde_json::to_string(&bounded).unwrap();
        let deserialized: TestBounded = serde_json::from_str(&serialized).unwrap();
        assert_eq!(*bounded, *deserialized);

        type TestStrictBounded = StrictBounded<1, 10>;
        let strict = TestStrictBounded::new(5.0).unwrap();
        let serialized = serde_json::to_string(&strict).unwrap();
        let deserialized: TestStrictBounded = serde_json::from_str(&serialized).unwrap();
        assert_eq!(*strict, *deserialized);
    }
}

/// A newtype wrapper for positive floating point values within exclusive bounds.
///
/// This type ensures that the wrapped value is positive and falls strictly within the
/// specified bounds (exclusive). The bounds are specified as generic const parameters,
/// making each combination of bounds a distinct type.
///
/// # Type Parameters
///
/// - `MIN`: The minimum bound (exclusive, must be positive)
/// - `MAX`: The maximum bound (exclusive, must be positive and > MIN)
///
/// # Examples
///
/// ```
/// use lasprs::StrictBounded;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// type StrictRange = StrictBounded<0, 10>; // Values between 0.0 and 10.0 (exclusive)
///
/// let value = StrictRange::new(5.0)?;  // OK
/// let value = StrictRange::new(0.1)?;  // OK
/// let value = StrictRange::new(9.9)?;  // OK
///
/// // These would fail:
/// // let invalid = StrictRange::new(0.0)?;  // Error: not > 0
/// // let invalid = StrictRange::new(10.0)?; // Error: not < 10
/// # Ok(())
/// # }
/// ```
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
pub struct StrictBounded<const MIN: i32, const MAX: i32>(Flt);

impl<const MIN: i32, const MAX: i32> StrictBounded<MIN, MAX> {
    /// Create a new strictly bounded positive floating point value.
    /// The value must be positive and strictly within the specified bounds (exclusive).
    pub fn new(value: Flt) -> Result<Self> {
        let min = MIN as Flt;
        let max = MAX as Flt;

        debug_assert!(min < max);
        ensure!(
            value > min && value < max,
            ExclusiveValueOutOfRangeSnafu { min, max, value }
        );
        Ok(Self(value))
    }
}

impl<const MIN: i32, const MAX: i32> TryFrom<Flt> for StrictBounded<MIN, MAX> {
    type Error = ValidationError;

    fn try_from(value: Flt) -> Result<Self> {
        Self::new(value)
    }
}

impl<const MIN: i32, const MAX: i32> Deref for StrictBounded<MIN, MAX> {
    type Target = Flt;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}