source-stream-0.rs/ascii/src/converters.rs
2025-11-18 13:05:26 +03:00

75 lines
1.7 KiB
Rust

use crate::AsciiChar;
pub trait AsciiCharConvertable {
fn asAsciiChar(&self) -> AsciiChar;
}
impl AsciiCharConvertable for char {
fn asAsciiChar(&self) -> AsciiChar {
let raw = *self as u32;
if raw < 128 {
return AsciiChar::ASCII(raw as u8);
} else {
return AsciiChar::NOT_ASCII;
}
}
}
impl AsciiCharConvertable for u8 {
fn asAsciiChar(&self) -> AsciiChar {
if *self < 128 {
return AsciiChar::ASCII(*self);
} else {
return AsciiChar::NOT_ASCII;
}
}
}
macro_rules! convert_unsigned {
() => {};
($t0:ty $(, $tN:ty)* $(,)?) => {
impl AsciiCharConvertable for $t0 {
fn asAsciiChar(&self) -> AsciiChar {
if *self < 128 {
return AsciiChar::ASCII(*self as u8);
} else {
return AsciiChar::NOT_ASCII;
}
}
}
convert_unsigned!($($tN ,)*);
}
}
convert_unsigned!(u16, u32, u64);
impl AsciiCharConvertable for i8 {
fn asAsciiChar(&self) -> AsciiChar {
if 0 <= *self {
return AsciiChar::ASCII(*self as u8);
} else {
return AsciiChar::NOT_ASCII;
}
}
}
macro_rules! convert_signed {
() => {};
($t0:ty $(, $tN:ty)* $(,)?) => {
impl AsciiCharConvertable for $t0 {
fn asAsciiChar(&self) -> AsciiChar {
if 0 <= *self && *self < 128 {
return AsciiChar::ASCII(*self as u8);
} else {
return AsciiChar::NOT_ASCII;
}
}
}
convert_unsigned!($($tN ,)*);
}
}
convert_signed!(i16, i32, i64);