use core::{cmp::Ordering, ops::Bound};
use super::{Domain, Iterable};
impl Domain for u16 {
const DISCRETE: bool = true;
#[must_use]
#[allow(clippy::arithmetic_side_effects)]
fn predecessor(&self) -> Option<Self> {
match *self {
Self::MIN => None,
_ => Some(self - 1),
}
}
#[must_use]
#[allow(clippy::arithmetic_side_effects)]
fn successor(&self) -> Option<Self> {
match *self {
Self::MAX => None,
_ => Some(self + 1),
}
}
#[must_use]
fn minimum() -> Bound<Self> {
Bound::Included(Self::MIN)
}
#[must_use]
fn maximum() -> Bound<Self> {
Bound::Included(Self::MAX)
}
#[must_use]
#[allow(clippy::shadow_reuse, clippy::arithmetic_side_effects)]
fn shares_neighbour_with(&self, other: &Self) -> bool {
let (big, small) = match self.cmp(other) {
Ordering::Less => (other, self),
Ordering::Equal => return false,
Ordering::Greater => (self, other),
};
big - small == 2
}
}
impl Iterable for u16 {
type Output = Self;
fn next(&self) -> Option<Self::Output> {
if *self == Self::MAX {
None
} else {
#[allow(clippy::arithmetic_side_effects)]
Some(*self + 1)
}
}
}
#[cfg(test)]
mod tests {
use crate::Domain;
#[test]
fn is_next_to() {
assert!(u16::MIN.is_next_to(&(u16::MIN + 1)));
assert!((u16::MIN + 1).is_next_to(&u16::MIN));
assert!(!u16::MIN.is_next_to(&(u16::MIN + 2)));
assert!(!u16::MIN.is_next_to(&u16::MAX));
assert!(!u16::MAX.is_next_to(&u16::MIN));
}
#[test]
fn shares_neighbour_with() {
assert!(!u16::MIN.shares_neighbour_with(&u16::MIN));
assert!(!42_u16.shares_neighbour_with(&45));
assert!(!45_u16.shares_neighbour_with(&42));
assert!(42_u16.shares_neighbour_with(&44));
assert!(44_u16.shares_neighbour_with(&42));
assert!(!u16::MIN.shares_neighbour_with(&u16::MAX));
assert!(!u16::MAX.shares_neighbour_with(&u16::MIN));
}
}