use crate::{
Ascii,
Charset,
CharsetCodec,
CharsetDecodeError,
CharsetDecodeErrorKind,
CharsetDecodeResult,
CharsetEncodeError,
CharsetEncodeErrorKind,
CharsetEncodeResult,
DecodeStatus,
};
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct AsciiCodec;
impl AsciiCodec {
#[must_use]
#[inline]
pub const fn charset(self) -> Charset {
Charset::ASCII
}
#[must_use]
#[inline]
pub const fn max_units_per_char(self) -> usize {
1
}
}
impl CharsetCodec for AsciiCodec {
type Unit = u8;
#[inline]
fn charset(&self) -> Charset {
Charset::ASCII
}
#[inline]
fn max_units_per_char(&self) -> usize {
1
}
#[inline]
fn decode_one(&self, input: &[u8], index: usize) -> CharsetDecodeResult<DecodeStatus> {
if index > input.len() {
let kind = CharsetDecodeErrorKind::MalformedSequence { value: None };
return Err(CharsetDecodeError::new(Charset::ASCII, kind, index));
}
if index == input.len() {
return Ok(DecodeStatus::NeedMore {
required: index + 1,
available: 0,
});
}
let value = input[index];
if value > Ascii::MAX_BYTE {
let kind = CharsetDecodeErrorKind::MalformedSequence {
value: Some(value as u32),
};
return Err(CharsetDecodeError::new(Charset::ASCII, kind, index));
}
Ok(DecodeStatus::Complete {
value: value as char,
consumed: 1,
})
}
#[inline]
fn encode_one(&self, ch: char, output: &mut [u8], index: usize) -> CharsetEncodeResult<usize> {
if index >= output.len() {
let kind = CharsetEncodeErrorKind::BufferTooSmall {
required: index + 1,
available: 0,
};
return Err(CharsetEncodeError::new(Charset::ASCII, kind, index));
}
if ch > Ascii::MAX_CHAR {
let kind = CharsetEncodeErrorKind::UnmappableCharacter { value: ch as u32 };
return Err(CharsetEncodeError::new(Charset::ASCII, kind, index));
}
output[index] = ch as u8;
Ok(1)
}
}