#![allow(clippy::upper_case_acronyms)]
use super::*;
use core::cmp::Ordering;
use core::convert::TryFrom;
#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct CharULE([u8; 3]);
unsafe impl ULE for CharULE {
#[inline]
fn validate_byte_slice(bytes: &[u8]) -> Result<(), ZeroVecError> {
if bytes.len() % 3 != 0 {
return Err(ZeroVecError::length::<Self>(bytes.len()));
}
for chunk in bytes.chunks_exact(3) {
#[allow(clippy::indexing_slicing)]
let u = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], 0]);
char::try_from(u).map_err(|_| ZeroVecError::parse::<Self>())?;
}
Ok(())
}
}
impl AsULE for char {
type ULE = CharULE;
#[inline]
fn to_unaligned(self) -> Self::ULE {
let [u0, u1, u2, _u3] = u32::from(self).to_le_bytes();
CharULE([u0, u1, u2])
}
#[inline]
fn from_unaligned(unaligned: Self::ULE) -> Self {
unsafe {
Self::from_u32_unchecked(u32::from_le_bytes([
unaligned.0[0],
unaligned.0[1],
unaligned.0[2],
0,
]))
}
}
}
impl PartialOrd for CharULE {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
char::from_unaligned(*self).partial_cmp(&char::from_unaligned(*other))
}
}
impl Ord for CharULE {
fn cmp(&self, other: &Self) -> Ordering {
char::from_unaligned(*self).cmp(&char::from_unaligned(*other))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse() {
let chars = ['w', 'ω', '文', '𑄃', '🙃'];
let char_ules: Vec<CharULE> = chars.iter().copied().map(char::to_unaligned).collect();
let char_bytes: &[u8] = CharULE::as_byte_slice(&char_ules);
let parsed_ules: &[CharULE] = CharULE::parse_byte_slice(char_bytes).unwrap();
assert_eq!(char_ules, parsed_ules);
let parsed_chars: Vec<char> = parsed_ules
.iter()
.copied()
.map(char::from_unaligned)
.collect();
assert_eq!(&chars, parsed_chars.as_slice());
assert_eq!(
&[119, 0, 0, 201, 3, 0, 135, 101, 0, 3, 17, 1, 67, 246, 1],
char_bytes
);
}
#[test]
fn test_failures() {
let u32s = [119, 0xD800, 120];
let u32_ules: Vec<RawBytesULE<4>> = u32s
.iter()
.copied()
.map(<u32 as AsULE>::to_unaligned)
.collect();
let u32_bytes: &[u8] = RawBytesULE::<4>::as_byte_slice(&u32_ules);
let parsed_ules_result = CharULE::parse_byte_slice(u32_bytes);
assert!(matches!(parsed_ules_result, Err(_)));
let u32s = [0x20FFFF];
let u32_ules: Vec<RawBytesULE<4>> = u32s
.iter()
.copied()
.map(<u32 as AsULE>::to_unaligned)
.collect();
let u32_bytes: &[u8] = RawBytesULE::<4>::as_byte_slice(&u32_ules);
let parsed_ules_result = CharULE::parse_byte_slice(u32_bytes);
assert!(matches!(parsed_ules_result, Err(_)));
}
}