mod fields;
mod key;
mod value;
use core::cmp::Ordering;
#[cfg(feature = "alloc")]
use core::str::FromStr;
pub use fields::Fields;
#[doc(inline)]
pub use key::{key, Key};
pub use value::Value;
#[cfg(feature = "alloc")]
use super::ExtensionType;
#[cfg(feature = "alloc")]
use crate::parser::SubtagIterator;
#[cfg(feature = "alloc")]
use crate::parser::{parse_language_identifier_from_iter, ParseError, ParserMode};
#[cfg(feature = "alloc")]
use crate::shortvec::ShortBoxSlice;
use crate::subtags;
use crate::LanguageIdentifier;
#[cfg(feature = "alloc")]
use litemap::LiteMap;
pub(crate) const TRANSFORM_EXT_CHAR: char = 't';
pub(crate) const TRANSFORM_EXT_STR: &str = "t";
#[derive(Clone, PartialEq, Eq, Debug, Default, Hash)]
#[allow(clippy::exhaustive_structs)] pub struct Transform {
pub lang: Option<LanguageIdentifier>,
pub fields: Fields,
}
impl Transform {
#[inline]
pub const fn new() -> Self {
Self {
lang: None,
fields: Fields::new(),
}
}
#[inline]
#[cfg(feature = "alloc")]
pub fn try_from_str(s: &str) -> Result<Self, ParseError> {
Self::try_from_utf8(s.as_bytes())
}
#[cfg(feature = "alloc")]
pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, ParseError> {
let mut iter = SubtagIterator::new(code_units);
let ext = iter.next().ok_or(ParseError::InvalidExtension)?;
if let ExtensionType::Transform = ExtensionType::try_from_byte_slice(ext)? {
return Self::try_from_iter(&mut iter);
}
Err(ParseError::InvalidExtension)
}
pub fn is_empty(&self) -> bool {
self.lang.is_none() && self.fields.is_empty()
}
pub fn clear(&mut self) {
self.lang = None;
self.fields.clear();
}
#[expect(clippy::type_complexity)]
pub(crate) fn as_tuple(
&self,
) -> (
Option<(
subtags::Language,
Option<subtags::Script>,
Option<subtags::Region>,
&subtags::Variants,
)>,
&Fields,
) {
(self.lang.as_ref().map(|l| l.as_tuple()), &self.fields)
}
pub fn total_cmp(&self, other: &Self) -> Ordering {
self.as_tuple().cmp(&other.as_tuple())
}
#[cfg(feature = "alloc")]
pub(crate) fn try_from_iter(iter: &mut SubtagIterator) -> Result<Self, ParseError> {
let mut tlang = None;
let mut tfields = LiteMap::new();
if let Some(subtag) = iter.peek() {
if subtags::Language::try_from_utf8(subtag).is_ok() {
tlang = Some(parse_language_identifier_from_iter(
iter,
ParserMode::Partial,
)?);
}
}
let mut current_tkey = None;
let mut current_tvalue = ShortBoxSlice::new();
let mut has_current_tvalue = false;
while let Some(subtag) = iter.peek() {
if let Some(tkey) = current_tkey {
if let Ok(val) = Value::parse_subtag(subtag) {
has_current_tvalue = true;
if let Some(val) = val {
current_tvalue.push(val);
}
} else {
if !has_current_tvalue {
return Err(ParseError::InvalidExtension);
}
tfields.try_insert(tkey, Value::from_short_slice_unchecked(current_tvalue));
current_tkey = None;
current_tvalue = ShortBoxSlice::new();
has_current_tvalue = false;
continue;
}
} else if let Ok(tkey) = Key::try_from_utf8(subtag) {
current_tkey = Some(tkey);
} else {
break;
}
iter.next();
}
if let Some(tkey) = current_tkey {
if !has_current_tvalue {
return Err(ParseError::InvalidExtension);
}
tfields.try_insert(tkey, Value::from_short_slice_unchecked(current_tvalue));
}
if tlang.is_none() && tfields.is_empty() {
Err(ParseError::InvalidExtension)
} else {
Ok(Self {
lang: tlang,
fields: tfields.into(),
})
}
}
pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F, with_ext: bool) -> Result<(), E>
where
F: FnMut(&str) -> Result<(), E>,
{
if self.is_empty() {
return Ok(());
}
if with_ext {
f(TRANSFORM_EXT_STR)?;
}
if let Some(lang) = &self.lang {
lang.for_each_subtag_str_lowercased(f)?;
}
self.fields.for_each_subtag_str(f)
}
}
#[cfg(feature = "alloc")]
impl FromStr for Transform {
type Err = ParseError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from_str(s)
}
}
writeable::impl_display_with_writeable!(Transform, #[cfg(feature = "alloc")]);
impl writeable::Writeable for Transform {
fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
if self.is_empty() {
return Ok(());
}
sink.write_char(TRANSFORM_EXT_CHAR)?;
if let Some(lang) = &self.lang {
sink.write_char('-')?;
lang.write_lowercased_to(sink)?;
}
if !self.fields.is_empty() {
sink.write_char('-')?;
writeable::Writeable::write_to(&self.fields, sink)?;
}
Ok(())
}
fn writeable_length_hint(&self) -> writeable::LengthHint {
if self.is_empty() {
return writeable::LengthHint::exact(0);
}
let mut result = writeable::LengthHint::exact(1);
if let Some(lang) = &self.lang {
result += writeable::Writeable::writeable_length_hint(lang) + 1;
}
if !self.fields.is_empty() {
result += writeable::Writeable::writeable_length_hint(&self.fields) + 1;
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_transform_extension_fromstr() {
let te: Transform = "t-en-us-h0-hybrid"
.parse()
.expect("Failed to parse Transform");
assert_eq!(te.to_string(), "t-en-us-h0-hybrid");
let te: Result<Transform, _> = "t".parse();
assert!(te.is_err());
}
}