1use crate::parser::*;
6use crate::subtags::Subtag;
7use crate::{LanguageIdentifier, extensions, subtags};
8#[cfg(feature = "alloc")]
9use alloc::borrow::Cow;
10use core::cmp::Ordering;
11#[cfg(feature = "alloc")]
12use core::str::FromStr;
13
14#[derive(#[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl ::core::cmp::PartialEq for Locale {
#[inline]
fn eq(&self, other: &Locale) -> bool {
self.id == other.id && self.extensions == other.extensions
}
}PartialEq, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl ::core::cmp::Eq for Locale {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<LanguageIdentifier>;
let _: ::core::cmp::AssertParamIsEq<extensions::Extensions>;
}
}Eq, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl ::core::clone::Clone for Locale {
#[inline]
fn clone(&self) -> Locale {
Locale {
id: ::core::clone::Clone::clone(&self.id),
extensions: ::core::clone::Clone::clone(&self.extensions),
}
}
}Clone, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl ::core::hash::Hash for Locale {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.id, state);
::core::hash::Hash::hash(&self.extensions, state)
}
}Hash)] #[allow(clippy::exhaustive_structs)] pub struct Locale {
103 pub id: LanguageIdentifier,
105 pub extensions: extensions::Extensions,
107}
108
109#[test]
110#[cfg(target_pointer_width = "64")]
112fn test_sizes() {
113 assert_eq!(size_of::<subtags::Language>(), 3);
114 assert_eq!(size_of::<subtags::Script>(), 4);
115 assert_eq!(size_of::<subtags::Region>(), 3);
116 assert_eq!(size_of::<subtags::Variant>(), 8);
117 assert_eq!(size_of::<subtags::Variants>(), 16);
118 assert_eq!(size_of::<LanguageIdentifier>(), 32);
119
120 assert_eq!(size_of::<extensions::transform::Transform>(), 56);
121 assert_eq!(size_of::<Option<LanguageIdentifier>>(), 32);
122 assert_eq!(size_of::<extensions::transform::Fields>(), 24);
123
124 assert_eq!(size_of::<extensions::unicode::Attributes>(), 16);
125 assert_eq!(size_of::<extensions::unicode::Keywords>(), 24);
126 assert_eq!(size_of::<Vec<extensions::other::Other>>(), 24);
127 assert_eq!(size_of::<extensions::private::Private>(), 16);
128 assert_eq!(size_of::<extensions::Extensions>(), 136);
129
130 assert_eq!(size_of::<Locale>(), 168);
131}
132
133impl Locale {
134 pub const UNKNOWN: Self = const {
match crate::Locale::try_from_utf8_with_single_variant_single_keyword_unicode_extension("und".as_bytes())
{
Ok((language, script, region, variant, keyword)) =>
crate::Locale {
id: crate::LanguageIdentifier {
language,
script,
region,
variants: match variant {
Some(v) => crate::subtags::Variants::from_variant(v),
None => crate::subtags::Variants::new(),
},
},
extensions: match keyword {
Some((key, value)) =>
crate::extensions::Extensions::from_unicode(crate::extensions::unicode::Unicode {
keywords: crate::extensions::unicode::Keywords::new_single(key,
crate::extensions::unicode::Value::from_subtag(value)),
attributes: crate::extensions::unicode::Attributes::new(),
}),
None => crate::extensions::Extensions::new(),
},
},
_ => {
::core::panicking::panic_fmt(format_args!("Invalid locale: und . Note the locale! macro only supports up to one variant tag; and one unicode keyword, other extension are not supported. Use runtime parsing instead."));
}
}
}crate::locale!("und");
136
137 #[inline]
154 #[cfg(feature = "alloc")]
155 pub fn try_from_str(s: &str) -> Result<Self, ParseError> {
156 Self::try_from_utf8(s.as_bytes())
157 }
158
159 #[cfg(feature = "alloc")]
163 pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, ParseError> {
164 parse_locale(code_units)
165 }
166
167 #[cfg(feature = "alloc")]
184 pub fn normalize_utf8(input: &[u8]) -> Result<Cow<'_, str>, ParseError> {
185 let locale = Self::try_from_utf8(input)?;
186 Ok(writeable::to_string_or_borrow(&locale, input))
187 }
188
189 #[cfg(feature = "alloc")]
206 pub fn normalize(input: &str) -> Result<Cow<'_, str>, ParseError> {
207 Self::normalize_utf8(input.as_bytes())
208 }
209
210 pub fn strict_cmp(&self, other: &[u8]) -> Ordering {
265 writeable::cmp_utf8(self, other)
266 }
267
268 #[expect(clippy::type_complexity)]
269 pub(crate) fn as_tuple(
270 &self,
271 ) -> (
272 (
273 subtags::Language,
274 Option<subtags::Script>,
275 Option<subtags::Region>,
276 &subtags::Variants,
277 ),
278 (
279 (
280 &extensions::unicode::Attributes,
281 &extensions::unicode::Keywords,
282 ),
283 (
284 Option<(
285 subtags::Language,
286 Option<subtags::Script>,
287 Option<subtags::Region>,
288 &subtags::Variants,
289 )>,
290 &extensions::transform::Fields,
291 ),
292 &extensions::private::Private,
293 &[extensions::other::Other],
294 ),
295 ) {
296 (self.id.as_tuple(), self.extensions.as_tuple())
297 }
298
299 pub fn total_cmp(&self, other: &Self) -> Ordering {
375 self.as_tuple().cmp(&other.as_tuple())
376 }
377
378 #[cfg(feature = "alloc")]
404 pub fn normalizing_eq(&self, other: &str) -> bool {
405 macro_rules! subtag_matches {
406 ($T:ty, $iter:ident, $expected:expr) => {
407 $iter
408 .next()
409 .map(|b| <$T>::try_from_utf8(b) == Ok($expected))
410 .unwrap_or(false)
411 };
412 }
413
414 let mut iter = SubtagIterator::new(other.as_bytes());
415 if !subtag_matches!(subtags::Language, iter, self.id.language) {
416 return false;
417 }
418 if let Some(ref script) = self.id.script
419 && !subtag_matches!(subtags::Script, iter, *script)
420 {
421 return false;
422 }
423 if let Some(ref region) = self.id.region
424 && !subtag_matches!(subtags::Region, iter, *region)
425 {
426 return false;
427 }
428 for variant in self.id.variants.iter() {
429 if !subtag_matches!(subtags::Variant, iter, *variant) {
430 return false;
431 }
432 }
433 if !self.extensions.is_empty() {
434 match extensions::Extensions::try_from_iter(&mut iter) {
435 Ok(exts) => {
436 if self.extensions != exts {
437 return false;
438 }
439 }
440 Err(_) => {
441 return false;
442 }
443 }
444 }
445 iter.next().is_none()
446 }
447
448 #[doc(hidden)] #[expect(clippy::type_complexity)]
450 pub const fn try_from_utf8_with_single_variant_single_keyword_unicode_extension(
451 code_units: &[u8],
452 ) -> Result<
453 (
454 subtags::Language,
455 Option<subtags::Script>,
456 Option<subtags::Region>,
457 Option<subtags::Variant>,
458 Option<(extensions::unicode::Key, Option<Subtag>)>,
459 ),
460 ParseError,
461 > {
462 parse_locale_with_single_variant_single_keyword_unicode_keyword_extension(
463 code_units,
464 ParserMode::Locale,
465 )
466 }
467
468 pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F) -> Result<(), E>
469 where
470 F: FnMut(&str) -> Result<(), E>,
471 {
472 self.id.for_each_subtag_str(f)?;
473 self.extensions.for_each_subtag_str(f)?;
474 Ok(())
475 }
476}
477
478impl AsRef<LanguageIdentifier> for Locale {
479 fn as_ref(&self) -> &LanguageIdentifier {
480 &self.id
481 }
482}
483
484#[cfg(feature = "alloc")]
486impl FromStr for Locale {
487 type Err = ParseError;
488
489 #[inline]
490 fn from_str(s: &str) -> Result<Self, Self::Err> {
491 Self::try_from_str(s)
492 }
493}
494
495impl From<LanguageIdentifier> for Locale {
496 fn from(id: LanguageIdentifier) -> Self {
497 Self {
498 id,
499 extensions: extensions::Extensions::default(),
500 }
501 }
502}
503
504impl From<Locale> for LanguageIdentifier {
505 fn from(loc: Locale) -> Self {
506 loc.id
507 }
508}
509
510impl core::fmt::Debug for Locale {
511 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
512 writeable::Writeable::write_to(self, f)
513 }
514}
515
516impl writeable::Writeable for Locale {
fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W)
-> core::fmt::Result {
let mut initial = true;
self.for_each_subtag_str(&mut |subtag|
{
if initial {
initial = false;
} else { sink.write_char('-')?; }
sink.write_str(subtag)
})
}
#[inline]
fn writeable_length_hint(&self) -> writeable::LengthHint {
let mut result = writeable::LengthHint::exact(0);
let mut initial = true;
self.for_each_subtag_str::<core::convert::Infallible,
_>(&mut |subtag|
{
if initial { initial = false; } else { result += 1; }
result += subtag.len();
Ok(())
}).expect("infallible");
result
}
fn writeable_borrow(&self) -> Option<&str> {
let selff = self;
if selff.extensions.is_empty() {
selff.id.writeable_borrow()
} else { None }
}
}
impl core::fmt::Display for Locale {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
::writeable::Writeable::write_to(&self, f)
}
}impl_writeable_for_each_subtag_str_no_test!(Locale, selff, selff.extensions.is_empty() => selff.id.writeable_borrow());
517
518#[test]
519fn test_writeable() {
520 use writeable::assert_writeable_eq;
521 assert_writeable_eq!(Locale::UNKNOWN, "und");
522 assert_writeable_eq!("und-001".parse::<Locale>().unwrap(), "und-001");
523 assert_writeable_eq!("und-Mymr".parse::<Locale>().unwrap(), "und-Mymr");
524 assert_writeable_eq!("my-Mymr-MM".parse::<Locale>().unwrap(), "my-Mymr-MM");
525 assert_writeable_eq!(
526 "my-Mymr-MM-posix".parse::<Locale>().unwrap(),
527 "my-Mymr-MM-posix",
528 );
529 assert_writeable_eq!(
530 "zh-macos-posix".parse::<Locale>().unwrap(),
531 "zh-macos-posix",
532 );
533 assert_writeable_eq!(
534 "my-t-my-d0-zawgyi".parse::<Locale>().unwrap(),
535 "my-t-my-d0-zawgyi",
536 );
537 assert_writeable_eq!(
538 "ar-SA-u-ca-islamic-civil".parse::<Locale>().unwrap(),
539 "ar-SA-u-ca-islamic-civil",
540 );
541 assert_writeable_eq!(
542 "en-001-x-foo-bar".parse::<Locale>().unwrap(),
543 "en-001-x-foo-bar",
544 );
545 assert_writeable_eq!("und-t-m0-true".parse::<Locale>().unwrap(), "und-t-m0-true",);
546}
547
548impl From<subtags::Language> for Locale {
557 fn from(language: subtags::Language) -> Self {
558 Self {
559 id: language.into(),
560 extensions: extensions::Extensions::new(),
561 }
562 }
563}
564
565impl From<Option<subtags::Script>> for Locale {
574 fn from(script: Option<subtags::Script>) -> Self {
575 Self {
576 id: script.into(),
577 extensions: extensions::Extensions::new(),
578 }
579 }
580}
581
582impl From<Option<subtags::Region>> for Locale {
591 fn from(region: Option<subtags::Region>) -> Self {
592 Self {
593 id: region.into(),
594 extensions: extensions::Extensions::new(),
595 }
596 }
597}
598
599impl
618 From<(
619 subtags::Language,
620 Option<subtags::Script>,
621 Option<subtags::Region>,
622 )> for Locale
623{
624 fn from(
625 lsr: (
626 subtags::Language,
627 Option<subtags::Script>,
628 Option<subtags::Region>,
629 ),
630 ) -> Self {
631 Self {
632 id: lsr.into(),
633 extensions: extensions::Extensions::new(),
634 }
635 }
636}