pub(crate) const MAX_DEPTH: usize = 20;
#[inline]
#[deprecated(note = "use `try_recursion_guard` instead")]
pub fn recursion_guard(
depth: usize,
f: impl FnOnce(usize) -> (usize, Option<usize>),
) -> (usize, Option<usize>) {
if depth > MAX_DEPTH {
(0, None)
} else {
f(depth + 1)
}
}
#[inline]
pub fn try_recursion_guard(
depth: usize,
f: impl FnOnce(usize) -> Result<(usize, Option<usize>), crate::MaxRecursionReached>,
) -> Result<(usize, Option<usize>), crate::MaxRecursionReached> {
if depth > MAX_DEPTH {
Err(crate::MaxRecursionReached {})
} else {
f(depth + 1)
}
}
#[inline]
pub fn and(lhs: (usize, Option<usize>), rhs: (usize, Option<usize>)) -> (usize, Option<usize>) {
let lower = lhs.0 + rhs.0;
let upper = lhs.1.and_then(|lhs| rhs.1.map(|rhs| lhs + rhs));
(lower, upper)
}
#[inline]
pub fn and_all(hints: &[(usize, Option<usize>)]) -> (usize, Option<usize>) {
hints.iter().copied().fold((0, Some(0)), and)
}
#[inline]
pub fn or(lhs: (usize, Option<usize>), rhs: (usize, Option<usize>)) -> (usize, Option<usize>) {
let lower = std::cmp::min(lhs.0, rhs.0);
let upper = lhs
.1
.and_then(|lhs| rhs.1.map(|rhs| std::cmp::max(lhs, rhs)));
(lower, upper)
}
#[inline]
pub fn or_all(hints: &[(usize, Option<usize>)]) -> (usize, Option<usize>) {
if let Some(head) = hints.first().copied() {
hints[1..].iter().copied().fold(head, or)
} else {
(0, Some(0))
}
}
#[cfg(test)]
mod tests {
#[test]
fn and() {
assert_eq!((5, Some(5)), super::and((2, Some(2)), (3, Some(3))));
assert_eq!((5, None), super::and((2, Some(2)), (3, None)));
assert_eq!((5, None), super::and((2, None), (3, Some(3))));
assert_eq!((5, None), super::and((2, None), (3, None)));
}
#[test]
fn or() {
assert_eq!((2, Some(3)), super::or((2, Some(2)), (3, Some(3))));
assert_eq!((2, None), super::or((2, Some(2)), (3, None)));
assert_eq!((2, None), super::or((2, None), (3, Some(3))));
assert_eq!((2, None), super::or((2, None), (3, None)));
}
#[test]
fn and_all() {
assert_eq!((0, Some(0)), super::and_all(&[]));
assert_eq!(
(7, Some(7)),
super::and_all(&[(1, Some(1)), (2, Some(2)), (4, Some(4))])
);
assert_eq!(
(7, None),
super::and_all(&[(1, Some(1)), (2, Some(2)), (4, None)])
);
assert_eq!(
(7, None),
super::and_all(&[(1, Some(1)), (2, None), (4, Some(4))])
);
assert_eq!(
(7, None),
super::and_all(&[(1, None), (2, Some(2)), (4, Some(4))])
);
}
#[test]
fn or_all() {
assert_eq!((0, Some(0)), super::or_all(&[]));
assert_eq!(
(1, Some(4)),
super::or_all(&[(1, Some(1)), (2, Some(2)), (4, Some(4))])
);
assert_eq!(
(1, None),
super::or_all(&[(1, Some(1)), (2, Some(2)), (4, None)])
);
assert_eq!(
(1, None),
super::or_all(&[(1, Some(1)), (2, None), (4, Some(4))])
);
assert_eq!(
(1, None),
super::or_all(&[(1, None), (2, Some(2)), (4, Some(4))])
);
}
}