use core::ops::Bound;
use super::{Domain, Iterable};
impl Domain for char {
const DISCRETE: bool = true;
#[allow(clippy::as_conversions, clippy::integer_arithmetic, clippy::use_self)]
fn predecessor(&self) -> Option<Self> {
match Self::minimum() {
Bound::Included(min) => {
if *self == min {
None
} else {
let pre = *self as u32 - 1;
if pre == 0xdfff {
Some('\u{d7ff}')
} else {
core::char::from_u32(pre)
}
}
}
Bound::Excluded(_) | Bound::Unbounded => unreachable!(),
}
}
#[allow(clippy::as_conversions, clippy::integer_arithmetic, clippy::use_self)]
fn successor(&self) -> Option<Self> {
match Self::maximum() {
Bound::Included(max) => {
if *self == max {
None
} else {
let succ = *self as u32 + 1;
if succ == 0xd800 {
Some('\u{e000}')
} else {
core::char::from_u32(succ)
}
}
}
Bound::Excluded(_) | Bound::Unbounded => {
unreachable!()
}
}
}
fn minimum() -> Bound<Self> {
Bound::Included('\u{0}')
}
fn maximum() -> Bound<Self> {
Bound::Included('\u{10ffff}')
}
#[must_use]
#[allow(clippy::as_conversions)]
fn shares_neighbour_with(&self, other: &Self) -> bool {
(*self as u32).shares_neighbour_with(&(*other as u32))
}
}
impl Iterable for char {
type Output = Self;
#[allow(clippy::integer_arithmetic, clippy::as_conversions)]
fn next(&self) -> Option<Self::Output> {
self.successor()
}
}
#[cfg(test)]
mod tests {
use crate::domain::Domain;
#[test]
fn neighbour_chars() {
assert!('a'.is_next_to(&'b'));
assert!(!'\u{0}'.is_next_to(&'\u{10ffff}'));
assert!('\u{d7ff}'.is_next_to(&'\u{e000}'));
}
#[test]
fn distance_between() {
assert_eq!('a'.shares_neighbour_with(&'b'), false);
assert_eq!('a'.shares_neighbour_with(&'c'), true);
assert_eq!('c'.shares_neighbour_with(&'a'), true);
assert_eq!('a'.shares_neighbour_with(&'z'), false);
assert_eq!('z'.shares_neighbour_with(&'a'), false);
assert_eq!('A'.shares_neighbour_with(&'Z'), false);
assert_eq!('Z'.shares_neighbour_with(&'A'), false);
}
}