Files
texrra-engine/crates/texrra-tex-core/src/execution/xe_encoding.rs
T

255 lines
8.6 KiB
Rust

//! XeTeX physical input encodings. Decoded units retain their source bytes.
use std::{collections::BTreeSet, sync::Arc};
use super::{Dependency, Parameter, ParameterValue, State};
pub(super) mod icu;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) enum Encoding {
#[default]
Auto,
Utf8,
Bytes,
Utf16Le,
Utf16Be,
Legacy(Arc<str>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum XeLineFraming {
Bytes,
Utf16Le,
Utf16Be,
Auto,
}
impl XeLineFraming {
pub fn detect(data: &[u8]) -> (Self, usize) {
match data {
[0xfe, 0xff, ..] => (Self::Utf16Be, 2),
[0xff, 0xfe, ..] => (Self::Utf16Le, 2),
[0, n, ..] if *n != 0 => (Self::Utf16Be, 0),
[n, 0, ..] if *n != 0 => (Self::Utf16Le, 0),
[0xef, 0xbb, 0xbf, ..] => (Self::Bytes, 3),
_ => (Self::Bytes, 0),
}
}
pub fn unit_width(self) -> usize {
match self {
Self::Utf16Be | Self::Utf16Le => 2,
Self::Bytes | Self::Auto => 1,
}
}
pub fn code_unit(self, data: &[u8]) -> Option<u16> {
match self {
Self::Utf16Le => Some(u16::from_le_bytes(data.get(..2)?.try_into().unwrap())),
Self::Utf16Be => Some(u16::from_be_bytes(data.get(..2)?.try_into().unwrap())),
Self::Bytes | Self::Auto => data.first().map(|b| u16::from(*b)),
}
}
pub fn line_boundary(self, data: &[u8]) -> (usize, Option<u16>) {
let width = self.unit_width();
for (index, unit) in data.chunks_exact(width).enumerate() {
let code = self.code_unit(unit).unwrap();
if matches!(code, 10 | 13) {
return (index * width, Some(code));
}
}
(data.len(), None)
}
}
#[derive(Clone, Copy)]
pub(super) struct Character {
pub value: char,
pub start: usize,
pub end: usize,
}
impl Character {
pub fn cover(&mut self, other: Self) {
self.start = self.start.min(other.start);
self.end = self.end.max(other.end);
}
}
impl Encoding {
pub fn parse(name: &str) -> Result<Option<Self>, String> {
let builtin = match name.to_ascii_lowercase().as_str() {
"auto" => Self::Auto,
"utf8" => Self::Utf8,
"utf16" if cfg!(target_endian = "little") => Self::Utf16Le,
"utf16" | "utf16be" => Self::Utf16Be,
"utf16le" => Self::Utf16Le,
"bytes" => Self::Bytes,
_ => {
return Ok(icu::recognizes(name)?.then(|| Self::Legacy(Arc::from(name))));
}
};
Ok(Some(builtin))
}
pub fn framing(&self) -> XeLineFraming {
match self {
Self::Auto => XeLineFraming::Auto,
Self::Utf16Le => XeLineFraming::Utf16Le,
Self::Utf16Be => XeLineFraming::Utf16Be,
_ => XeLineFraming::Bytes,
}
}
pub fn resolve(&self, data: &[u8]) -> (Self, usize) {
if *self != Self::Auto {
return (self.clone(), 0);
}
let (framing, bom) = XeLineFraming::detect(data);
let encoding = match framing {
XeLineFraming::Utf16Le => Self::Utf16Le,
XeLineFraming::Utf16Be => Self::Utf16Be,
_ => Self::Utf8,
};
(encoding, bom)
}
/// Decode a complete physical line before TeX looks at any of its catcodes.
pub fn decode_line(
&self,
data: &[u8],
base: usize,
state: &State,
reads: &mut BTreeSet<Dependency>,
) -> Result<(Vec<Character>, usize), String> {
let (mut characters, warnings) = self.decode(data, base)?;
let parameter = Parameter::XeTeXinputnormalization;
reads.insert(Dependency::Parameter(parameter));
match state.parameter(parameter) {
ParameterValue::Integer(1) => characters = normalize(characters, true),
ParameterValue::Integer(2) => characters = normalize(characters, false),
_ => {}
}
while characters.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) {
characters.pop();
}
Ok((characters, warnings))
}
fn decode(&self, data: &[u8], base: usize) -> Result<(Vec<Character>, usize), String> {
let mut invalid_utf8 = 0;
let chars = match self {
Self::Auto => unreachable!("resolve the encoding at file open"),
Self::Utf8 => {
if let Ok(str) = std::str::from_utf8(data) {
str.char_indices()
.map(|(i, value)| Character {
value,
start: base + i,
end: base + i + value.len_utf8(),
})
.collect()
} else {
let mut chars = Vec::new();
let mut at = 0;
while at < data.len() {
let (value, length, bad) = decode_utf8_character(&data[at..]);
invalid_utf8 += usize::from(bad);
chars.push(Character {
value,
start: base + at,
end: base + at + length,
});
at += length;
}
chars
}
}
Self::Bytes => data
.iter()
.enumerate()
.map(|(i, byte)| Character {
value: char::from(*byte),
start: base + i,
end: base + i + 1,
})
.collect(),
Self::Utf16Le | Self::Utf16Be => {
let framing = self.framing();
let mut chars = Vec::new();
let mut at = 0;
while let Some(first) = framing.code_unit(&data[at..]) {
let second = framing.code_unit(&data[at + 2..]);
let (value, units) = utf16_character(first, second);
let end = at + 2 * units;
chars.push(Character {
value,
start: base + at,
end: base + end,
});
at = end;
}
if at < data.len() {
chars.push(Character {
value: char::REPLACEMENT_CHARACTER,
start: base + at,
end: base + data.len(),
});
}
chars
}
Self::Legacy(name) => icu::decode(name, data, base)?,
};
Ok((chars, invalid_utf8))
}
}
fn normalize(characters: Vec<Character>, composed: bool) -> Vec<Character> {
use unicode_normalization::char::decompose_canonical;
if characters.iter().all(|character| character.value.is_ascii()) {
return characters;
}
let mut decomposed = Vec::with_capacity(characters.len());
for character in characters {
decompose_canonical(character.value, |value| decomposed.push((value, character)));
}
crate::normalization::order_and_compose(decomposed, composed, Character::cover)
.into_iter()
.map(|(value, source)| Character { value, ..source })
.collect()
}
fn decode_utf8_character(input: &[u8]) -> (char, usize, bool) {
let first = input[0];
let (mut value, continuation) = match first {
0x00..=0xbf => return (char::from(first), 1, false),
0xc0..=0xdf => (u32::from(first & 0x1f), 1),
0xe0..=0xef => (u32::from(first & 0x0f), 2),
0xf0..=0xf7 => (u32::from(first & 0x07), 3),
_ => return (char::REPLACEMENT_CHARACTER, 1, true),
};
for at in 1..=continuation {
let Some(&b @ 0x80..=0xbf) = input.get(at) else {
return (char::REPLACEMENT_CHARACTER, at, true);
};
value = (value << 6) | u32::from(b & 0x3f);
}
match char::from_u32(value) {
Some(c) => (c, continuation + 1, false),
None => (char::REPLACEMENT_CHARACTER, continuation + 1, true),
}
}
fn utf16_character(first: u16, second: Option<u16>) -> (char, usize) {
if let (0xd800..=0xdbff, Some(low @ 0xdc00..=0xdfff)) = (first, second) {
let value = 0x10000 + ((u32::from(first) - 0xd800) << 10) + u32::from(low) - 0xdc00;
return (char::from_u32(value).unwrap(), 2);
}
(
char::from_u32(u32::from(first)).unwrap_or(char::REPLACEMENT_CHARACTER),
1,
)
}