use core::{char::from_u32, ops::Bound};
use super::{Domain, Iterable};
impl Domain for char {
const DISCRETE: bool = true;
#[inline]
#[allow(clippy::as_conversions, clippy::arithmetic_side_effects, 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 {
from_u32(pre)
}
}
}
Bound::Excluded(_) | Bound::Unbounded => unreachable!(),
}
}
#[inline]
#[allow(clippy::as_conversions, clippy::arithmetic_side_effects, 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 {
from_u32(succ)
}
}
}
Bound::Excluded(_) | Bound::Unbounded => {
unreachable!()
}
}
}
#[inline]
fn minimum() -> Bound<Self> {
Bound::Included('\u{0}')
}
#[inline]
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;
#[inline]
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!(!'a'.shares_neighbour_with(&'b'));
assert!('a'.shares_neighbour_with(&'c'));
assert!('c'.shares_neighbour_with(&'a'));
assert!(!'a'.shares_neighbour_with(&'z'));
assert!(!'z'.shares_neighbour_with(&'a'));
assert!(!'A'.shares_neighbour_with(&'Z'));
assert!(!'Z'.shares_neighbour_with(&'A'));
}
}