Skip to main content

sparse_ir_sve/
checks.rs

1//! Parameter checks shared by the `sparse-ir` crates
2
3use crate::error::Error;
4
5/// `Ok` if `value` is positive and finite
6pub fn require_positive_finite(name: &'static str, value: f64) -> Result<(), Error> {
7    if value > 0.0 && value.is_finite() {
8        Ok(())
9    } else {
10        Err(Error::InvalidParameter {
11            name,
12            value: format!("{value:?}"),
13            reason: "must be positive and finite".to_string(),
14        })
15    }
16}
17
18/// `Ok` if `value` is finite
19pub fn require_finite(name: &'static str, value: f64) -> Result<(), Error> {
20    if value.is_finite() {
21        Ok(())
22    } else {
23        Err(Error::InvalidParameter {
24            name,
25            value: format!("{value:?}"),
26            reason: "must be finite".to_string(),
27        })
28    }
29}
30
31/// `Ok` for an accuracy that selects the SVE: `None` (automatic) or a value
32/// in (0, 1)
33pub fn require_accuracy(name: &'static str, epsilon: Option<f64>) -> Result<(), Error> {
34    match epsilon {
35        Some(eps) if !(eps > 0.0 && eps < 1.0) => Err(Error::InvalidParameter {
36            name,
37            value: format!("{eps:?}"),
38            reason: "must be in (0, 1)".to_string(),
39        }),
40        _ => Ok(()),
41    }
42}
43
44/// `Ok` for a relative truncation threshold: `None` or a value in [0, 1),
45/// where 0 keeps every singular value
46pub fn require_threshold(name: &'static str, epsilon: Option<f64>) -> Result<(), Error> {
47    match epsilon {
48        Some(eps) if !(eps >= 0.0 && eps < 1.0) => Err(Error::InvalidParameter {
49            name,
50            value: format!("{eps:?}"),
51            reason: "must be in [0, 1)".to_string(),
52        }),
53        _ => Ok(()),
54    }
55}
56
57/// `Ok` unless `size` is `Some(0)`
58pub fn require_nonzero_size(name: &'static str, size: Option<usize>) -> Result<(), Error> {
59    match size {
60        Some(0) => Err(Error::InvalidParameter {
61            name,
62            value: "0".to_string(),
63            reason: "must be positive".to_string(),
64        }),
65        _ => Ok(()),
66    }
67}