use crate::{
ByteOrder,
Charset,
CharsetCodec,
CharsetDecodeError,
CharsetDecodeErrorKind,
CharsetDecodeResult,
CharsetEncodeError,
CharsetEncodeErrorKind,
CharsetEncodeProbe,
CharsetEncodeResult,
Unicode,
Utf16,
};
use core::num::NonZeroUsize;
use qubit_codec::Codec;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Utf16ByteCodec {
byte_order: ByteOrder,
}
impl Utf16ByteCodec {
#[inline(always)]
#[must_use]
pub const fn new(byte_order: ByteOrder) -> Self {
Self { byte_order }
}
#[inline(always)]
#[must_use]
pub const fn byte_order(self) -> ByteOrder {
self.byte_order
}
#[inline(always)]
#[must_use]
pub const fn charset(self) -> Charset {
Charset::from_utf16_byte_order(self.byte_order)
}
}
impl CharsetCodec for Utf16ByteCodec {
#[inline(always)]
fn charset(&self) -> Charset {
Charset::from_utf16_byte_order(self.byte_order)
}
}
impl CharsetEncodeProbe for Utf16ByteCodec {
#[inline(always)]
fn encode_len(
&self,
ch: char,
_index: usize,
) -> CharsetEncodeResult<usize> {
Ok(Utf16::unit_len(ch) * 2)
}
}
unsafe impl Codec for Utf16ByteCodec {
type Value = char;
type Unit = u8;
type DecodeError = CharsetDecodeError;
type EncodeError = CharsetEncodeError;
#[inline(always)]
fn min_units_per_value(&self) -> NonZeroUsize {
unsafe { NonZeroUsize::new_unchecked(2) }
}
#[inline(always)]
fn max_units_per_value(&self) -> NonZeroUsize {
unsafe { NonZeroUsize::new_unchecked(Utf16::MAX_BYTES_PER_CHAR) }
}
#[inline(always)]
unsafe fn decode_unchecked(
&self,
input: &[u8],
index: usize,
) -> CharsetDecodeResult<(char, NonZeroUsize)> {
let (ch, consumed) =
decode_bytes_prefix(input, index, self.byte_order)?;
debug_assert!(consumed.get() <= input.len() - index);
Ok((ch, consumed))
}
#[inline(always)]
unsafe fn encode_unchecked(
&self,
ch: &char,
output: &mut [u8],
index: usize,
) -> CharsetEncodeResult<usize> {
let written = encode_bytes_char(*ch, output, self.byte_order, index)?;
debug_assert_eq!(written, ch.len_utf16() * 2);
debug_assert!(written <= output.len() - index);
Ok(written)
}
}
fn decode_bytes_prefix(
input: &[u8],
index: usize,
byte_order: ByteOrder,
) -> CharsetDecodeResult<(char, NonZeroUsize)> {
let charset = Charset::from_utf16_byte_order(byte_order);
if index > input.len() {
let kind = CharsetDecodeErrorKind::InvalidInputIndex {
input_len: input.len(),
};
return Err(CharsetDecodeError::new(charset, kind, index));
}
let available = input.len() - index;
if available < 2 {
let kind = CharsetDecodeErrorKind::IncompleteSequence {
required: 2,
available,
};
return Err(CharsetDecodeError::new(charset, kind, index));
}
let first = read_ordered_u16(input, index, byte_order);
if Utf16::is_high_surrogate(first) {
if available < 4 {
let kind = CharsetDecodeErrorKind::IncompleteSequence {
required: 4,
available,
};
return Err(CharsetDecodeError::new(charset, kind, index));
}
let second = read_ordered_u16(input, index + 2, byte_order);
match Utf16::compose_pair(first, second).and_then(Unicode::to_char) {
Some(ch) => {
Ok((ch, unsafe { NonZeroUsize::new_unchecked(4) }))
}
None => {
let kind = CharsetDecodeErrorKind::MalformedSequence {
value: Some(second as u32),
};
Err(CharsetDecodeError::new(
charset,
kind,
required_index(index, 2),
)
.with_consumed(4))
}
}
} else if Utf16::is_low_surrogate(first) {
let kind = CharsetDecodeErrorKind::MalformedSequence {
value: Some(first as u32),
};
Err(CharsetDecodeError::new(charset, kind, index).with_consumed(2))
} else {
let ch = char::from_u32(first as u32)
.expect("non-surrogate UTF-16 unit is a scalar value");
Ok((ch, unsafe { NonZeroUsize::new_unchecked(2) }))
}
}
fn encode_bytes_char(
ch: char,
output: &mut [u8],
byte_order: ByteOrder,
index: usize,
) -> CharsetEncodeResult<usize> {
let charset = Charset::from_utf16_byte_order(byte_order);
if index > output.len() {
let kind = CharsetEncodeErrorKind::BufferTooSmall {
required: required_index(index, 2),
available: 0,
};
return Err(CharsetEncodeError::new(charset, kind, index));
}
let required = Utf16::unit_len(ch) * 2;
let available = output.len() - index;
if available < required {
let kind = CharsetEncodeErrorKind::BufferTooSmall {
required: required_index(index, required),
available,
};
return Err(CharsetEncodeError::new(charset, kind, index));
}
let code_point = ch as u32;
if required == 2 {
write_ordered_u16(output, index, code_point as u16, byte_order);
} else {
let high = Utf16::high_surrogate(code_point)
.expect("supplementary scalar has high surrogate");
let low = Utf16::low_surrogate(code_point)
.expect("supplementary scalar has low surrogate");
write_ordered_u16(output, index, high, byte_order);
write_ordered_u16(output, index + 2, low, byte_order);
}
Ok(required)
}
#[inline(always)]
const fn required_index(index: usize, required_units: usize) -> usize {
match index.checked_add(required_units) {
Some(required) => required,
None => usize::MAX,
}
}
#[inline(always)]
fn read_ordered_u16(input: &[u8], index: usize, byte_order: ByteOrder) -> u16 {
let bytes = [input[index], input[index + 1]];
match byte_order {
ByteOrder::BigEndian => u16::from_be_bytes(bytes),
ByteOrder::LittleEndian => u16::from_le_bytes(bytes),
}
}
#[inline(always)]
fn write_ordered_u16(
output: &mut [u8],
index: usize,
unit: u16,
byte_order: ByteOrder,
) {
let bytes = match byte_order {
ByteOrder::BigEndian => unit.to_be_bytes(),
ByteOrder::LittleEndian => unit.to_le_bytes(),
};
output[index..index + 2].copy_from_slice(&bytes);
}