custom_types/
custom_types.rsuse lineic::LinearInterpolator;
fn main() {
let interpolator: LinearInterpolator<1, u8, NumericUnicode> =
LinearInterpolator::new(0..=26, &[['a'.into()], ['z'.into()]]);
let result = interpolator.interpolate(17);
println!(
"The 17th letter of the alphabet is: {:?}",
NumericUnicode::to_string(&result)
);
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
struct NumericUnicode(u32);
impl NumericUnicode {
fn to_string(values: &[Self]) -> String {
values.iter().map(|v| char::from(*v)).collect()
}
}
impl From<char> for NumericUnicode {
fn from(value: char) -> NumericUnicode {
NumericUnicode(value as u32)
}
}
impl From<NumericUnicode> for char {
fn from(value: NumericUnicode) -> char {
if let Some(c) = std::char::from_u32(value.0) {
c
} else {
let mut distance = 1;
loop {
let below = value.0.checked_sub(distance);
if let Some(c) = below.and_then(std::char::from_u32) {
break c;
}
let above = value.0.checked_add(distance);
if let Some(c) = above.and_then(std::char::from_u32) {
break c;
}
distance += 1;
}
}
}
}
impl lineic::Numeric for NumericUnicode {
const MAX: Self = NumericUnicode(u32::MAX);
const ZERO: Self = NumericUnicode(0);
const ONE: Self = NumericUnicode(1);
fn abs(self) -> Self {
self
}
fn clamp(self, min: Self, max: Self) -> Self {
Self(if min > max {
std::cmp::Ord::clamp(self.0, min.0, max.0)
} else {
std::cmp::Ord::clamp(self.0, max.0, min.0)
})
}
fn from_usize(value: usize) -> Option<Self> {
u32::try_from(value).ok().map(Self)
}
fn into_f64(self) -> f64 {
self.0 as f64
}
fn from_f64(value: f64) -> Option<Self> {
if value < u32::MAX as f64 && value >= 0.0 {
Some(Self(value as u32))
} else {
None
}
}
fn checked_sub(self, other: Self) -> Option<Self> {
self.0.checked_sub(other.0).map(Self)
}
fn checked_add(self, other: Self) -> Option<Self> {
self.0.checked_add(other.0).map(Self)
}
fn checked_mul(self, other: Self) -> Option<Self> {
self.0.checked_mul(other.0).map(Self)
}
fn checked_div(self, other: Self) -> Option<Self> {
self.0.checked_div(other.0).map(Self)
}
}