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
//! Non-zero check returning an `Option`.
use super::U512;
impl U512 {
/// Returns `Some(self)` if the value is non-zero, or `None` if zero.
///
/// Useful for early-return patterns with the `?` operator where zero
/// inputs are invalid.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u512::U512;
///
/// let v = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 42]);
/// assert_eq!(v.non_zero(), Some(v));
///
/// let z = U512::ZERO;
/// assert_eq!(z.non_zero(), None);
/// ```
#[inline]
pub const fn non_zero(self) -> Option<U512> {
match self.const_eq(&U512::ZERO) {
true => None,
false => Some(self),
}
}
}
#[cfg(test)]
mod ai_tests {
use super::*;
/// Zero returns None.
#[test]
fn zero_is_none() {
assert_eq!(U512::ZERO.non_zero(), None);
}
/// Non-zero returns Some.
#[test]
fn nonzero_is_some() {
let v = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 1]);
assert_eq!(v.non_zero(), Some(v));
}
/// Large value returns Some.
#[test]
fn large_value() {
assert_eq!(U512::MAX.non_zero(), Some(U512::MAX));
}
/// MSB-only value returns Some.
#[test]
fn msb_only() {
let v = U512::from_be_limbs([1, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(v.non_zero(), Some(v));
}
}