pub const fn local_iso_iec_646_byte_to_char(b: u8) -> Result<char, ()> {
let ones: u8 = b & 0x0F;
let tens: u8 = (b & 0xF0) >> 4;
if ones > 9 || tens > 9 {
return Err(());
}
let cc: u8 = (tens * 10) + ones;
if cc >= 95 {
return Err(());
}
let c = (cc + 32) as char;
debug_assert!(!c.is_ascii_control());
Ok(c)
}
pub const fn char_to_local_iso_iec_646_byte(c: char) -> Result<u8, ()> {
if c.is_ascii_control() || c > '\x7E' {
return Err(());
}
let cc = (c as u8) - 32;
let ones: u8 = cc % 10;
let tens: u8 = cc / 10;
let b: u8 = (tens << 4) + ones;
Ok(b)
}
#[cfg(test)]
mod tests {
use super::{char_to_local_iso_iec_646_byte, local_iso_iec_646_byte_to_char};
#[test]
fn test_char_to_local_iso_iec_646_byte() {
let b = char_to_local_iso_iec_646_byte('a').unwrap();
assert_eq!(b, 0x65);
}
#[test]
fn test_local_iso_iec_646_byte_to_char() {
let c = local_iso_iec_646_byte_to_char(0x65).unwrap();
assert_eq!(c, 'a');
}
#[test]
fn test_iso_iec_646_encode_decode() {
for c in ' '..='~' {
let encoded = char_to_local_iso_iec_646_byte(c).unwrap();
let decoded = local_iso_iec_646_byte_to_char(encoded).unwrap();
assert_eq!(decoded, c);
}
}
}