1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::{provider::*, LocaleTransformError};
use icu_locid::subtags::{Language, Region, Script};
use icu_locid::LanguageIdentifier;
use icu_provider::prelude::*;
use crate::TransformResult;
/// Implements the *Add Likely Subtags* and *Remove Likely Subtags*
/// algorithms as defined in *[UTS #35: Likely Subtags]*.
///
/// # Examples
///
/// Add likely subtags:
///
/// ```
/// use icu::locid::locale;
/// use icu::locid_transform::{LocaleExpander, TransformResult};
///
/// let lc = LocaleExpander::new();
///
/// let mut locale = locale!("zh-CN");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
/// assert_eq!(locale, locale!("zh-Hans-CN"));
///
/// let mut locale = locale!("zh-Hant-TW");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Unmodified);
/// assert_eq!(locale, locale!("zh-Hant-TW"));
/// ```
///
/// Remove likely subtags:
///
/// ```
/// use icu::locid::locale;
/// use icu::locid_transform::{LocaleExpander, TransformResult};
///
/// let lc = LocaleExpander::new();
///
/// let mut locale = locale!("zh-Hans-CN");
/// assert_eq!(lc.minimize(&mut locale), TransformResult::Modified);
/// assert_eq!(locale, locale!("zh"));
///
/// let mut locale = locale!("zh");
/// assert_eq!(lc.minimize(&mut locale), TransformResult::Unmodified);
/// assert_eq!(locale, locale!("zh"));
/// ```
///
/// Normally, only CLDR locales with Basic or higher coverage are included. To include more
/// locales for maximization, use [`try_new_extended`](Self::try_new_extended_unstable):
///
/// ```
/// use icu::locid::locale;
/// use icu::locid_transform::{LocaleExpander, TransformResult};
///
/// let lc = LocaleExpander::new_extended();
///
/// let mut locale = locale!("atj");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
/// assert_eq!(locale, locale!("atj-Latn-CA"));
/// ```
///
/// [UTS #35: Likely Subtags]: https://www.unicode.org/reports/tr35/#Likely_Subtags
#[derive(Debug, Clone)]
pub struct LocaleExpander {
likely_subtags_l: DataPayload<LikelySubtagsForLanguageV1Marker>,
likely_subtags_sr: DataPayload<LikelySubtagsForScriptRegionV1Marker>,
likely_subtags_ext: Option<DataPayload<LikelySubtagsExtendedV1Marker>>,
}
struct LocaleExpanderBorrowed<'a> {
likely_subtags_l: &'a LikelySubtagsForLanguageV1<'a>,
likely_subtags_sr: &'a LikelySubtagsForScriptRegionV1<'a>,
likely_subtags_ext: Option<&'a LikelySubtagsExtendedV1<'a>>,
}
impl LocaleExpanderBorrowed<'_> {
fn get_l(&self, l: Language) -> Option<(Script, Region)> {
let key = &l.into_tinystr().to_unvalidated();
self.likely_subtags_l.language.get_copied(key).or_else(|| {
self.likely_subtags_ext
.and_then(|ext| ext.language.get_copied(key))
})
}
fn get_ls(&self, l: Language, s: Script) -> Option<Region> {
let key = &(
l.into_tinystr().to_unvalidated(),
s.into_tinystr().to_unvalidated(),
);
self.likely_subtags_l
.language_script
.get_copied(key)
.or_else(|| {
self.likely_subtags_ext
.and_then(|ext| ext.language_script.get_copied(key))
})
}
fn get_lr(&self, l: Language, r: Region) -> Option<Script> {
let key = &(
l.into_tinystr().to_unvalidated(),
r.into_tinystr().to_unvalidated(),
);
self.likely_subtags_l
.language_region
.get_copied(key)
.or_else(|| {
self.likely_subtags_ext
.and_then(|ext| ext.language_region.get_copied(key))
})
}
fn get_s(&self, s: Script) -> Option<(Language, Region)> {
let key = &s.into_tinystr().to_unvalidated();
self.likely_subtags_sr.script.get_copied(key).or_else(|| {
self.likely_subtags_ext
.and_then(|ext| ext.script.get_copied(key))
})
}
fn get_sr(&self, s: Script, r: Region) -> Option<Language> {
let key = &(
s.into_tinystr().to_unvalidated(),
r.into_tinystr().to_unvalidated(),
);
self.likely_subtags_sr
.script_region
.get_copied(key)
.or_else(|| {
self.likely_subtags_ext
.and_then(|ext| ext.script_region.get_copied(key))
})
}
fn get_r(&self, r: Region) -> Option<(Language, Script)> {
let key = &r.into_tinystr().to_unvalidated();
self.likely_subtags_sr.region.get_copied(key).or_else(|| {
self.likely_subtags_ext
.and_then(|ext| ext.region.get_copied(key))
})
}
fn get_und(&self) -> (Language, Script, Region) {
self.likely_subtags_l.und
}
}
#[inline]
fn update_langid(
language: Language,
script: Option<Script>,
region: Option<Region>,
langid: &mut LanguageIdentifier,
) -> TransformResult {
let mut modified = false;
if langid.language.is_empty() && !language.is_empty() {
langid.language = language;
modified = true;
}
if langid.script.is_none() && script.is_some() {
langid.script = script;
modified = true;
}
if langid.region.is_none() && region.is_some() {
langid.region = region;
modified = true;
}
if modified {
TransformResult::Modified
} else {
TransformResult::Unmodified
}
}
#[inline]
fn update_langid_minimize(
language: Language,
script: Option<Script>,
region: Option<Region>,
langid: &mut LanguageIdentifier,
) -> TransformResult {
let mut modified = false;
if langid.language != language {
langid.language = language;
modified = true;
}
if langid.script != script {
langid.script = script;
modified = true;
}
if langid.region != region {
langid.region = region;
modified = true;
}
if modified {
TransformResult::Modified
} else {
TransformResult::Unmodified
}
}
#[cfg(feature = "compiled_data")]
impl Default for LocaleExpander {
fn default() -> Self {
Self::new()
}
}
impl LocaleExpander {
/// Creates a [`LocaleExpander`] with compiled data for commonly-used locales
/// (locales with *Basic* or higher [CLDR coverage]).
///
/// Use this constructor if you want limited likely subtags for data-oriented use cases.
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// [CLDR coverage]: https://www.unicode.org/reports/tr35/tr35-info.html#Coverage_Levels
#[cfg(feature = "compiled_data")]
pub const fn new() -> Self {
LocaleExpander {
likely_subtags_l: DataPayload::from_static_ref(
crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_L_V1,
),
likely_subtags_sr: DataPayload::from_static_ref(
crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_SR_V1,
),
likely_subtags_ext: None,
}
}
/// Creates a [`LocaleExpander`] with compiled data for all locales.
///
/// Use this constructor if you want to include data for all locales, including ones
/// that may not have data for other services (i.e. [CLDR coverage] below *Basic*).
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// [CLDR coverage]: https://www.unicode.org/reports/tr35/tr35-info.html#Coverage_Levels
#[cfg(feature = "compiled_data")]
pub const fn new_extended() -> Self {
LocaleExpander {
likely_subtags_l: DataPayload::from_static_ref(
crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_L_V1,
),
likely_subtags_sr: DataPayload::from_static_ref(
crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_SR_V1,
),
likely_subtags_ext: Some(DataPayload::from_static_ref(
crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_EXT_V1,
)),
}
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::new_extended)]
pub fn try_new_extended_unstable<P>(
provider: &P,
) -> Result<LocaleExpander, LocaleTransformError>
where
P: DataProvider<LikelySubtagsForLanguageV1Marker>
+ DataProvider<LikelySubtagsForScriptRegionV1Marker>
+ DataProvider<LikelySubtagsExtendedV1Marker>
+ ?Sized,
{
let likely_subtags_l = provider.load(Default::default())?.take_payload()?;
let likely_subtags_sr = provider.load(Default::default())?.take_payload()?;
let likely_subtags_ext = Some(provider.load(Default::default())?.take_payload()?);
Ok(LocaleExpander {
likely_subtags_l,
likely_subtags_sr,
likely_subtags_ext,
})
}
icu_provider::gen_any_buffer_data_constructors!(locale: skip, options: skip, error: LocaleTransformError,
#[cfg(skip)]
functions: [
new_extended,
try_new_extended_with_any_provider,
try_new_extended_with_buffer_provider,
try_new_extended_unstable,
Self
]);
#[doc = icu_provider::gen_any_buffer_unstable_docs!(ANY, Self::new)]
pub fn try_new_with_any_provider(
provider: &(impl AnyProvider + ?Sized),
) -> Result<LocaleExpander, LocaleTransformError> {
Self::try_new_compat(&provider.as_downcasting())
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(BUFFER, Self::new)]
#[cfg(feature = "serde")]
pub fn try_new_with_buffer_provider(
provider: &(impl BufferProvider + ?Sized),
) -> Result<LocaleExpander, LocaleTransformError> {
Self::try_new_compat(&provider.as_deserializing())
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::new)]
pub fn try_new_unstable<P>(provider: &P) -> Result<LocaleExpander, LocaleTransformError>
where
P: DataProvider<LikelySubtagsForLanguageV1Marker>
+ DataProvider<LikelySubtagsForScriptRegionV1Marker>
+ ?Sized,
{
let likely_subtags_l = provider.load(Default::default())?.take_payload()?;
let likely_subtags_sr = provider.load(Default::default())?.take_payload()?;
Ok(LocaleExpander {
likely_subtags_l,
likely_subtags_sr,
likely_subtags_ext: None,
})
}
fn try_new_compat<P>(provider: &P) -> Result<LocaleExpander, LocaleTransformError>
where
P: DataProvider<LikelySubtagsForLanguageV1Marker>
+ DataProvider<LikelySubtagsForScriptRegionV1Marker>
+ DataProvider<LikelySubtagsExtendedV1Marker>
+ DataProvider<LikelySubtagsV1Marker>
+ ?Sized,
{
let payload_l = provider
.load(Default::default())
.and_then(DataResponse::take_payload);
let payload_sr = provider
.load(Default::default())
.and_then(DataResponse::take_payload);
let payload_ext = provider
.load(Default::default())
.and_then(DataResponse::take_payload);
let (likely_subtags_l, likely_subtags_sr, likely_subtags_ext) =
match (payload_l, payload_sr, payload_ext) {
(Ok(l), Ok(sr), Err(_)) => (l, sr, None),
(Ok(l), Ok(sr), Ok(ext)) => (l, sr, Some(ext)),
_ => {
let result: DataPayload<LikelySubtagsV1Marker> =
provider.load(Default::default())?.take_payload()?;
(
result.map_project_cloned(|st, _| {
LikelySubtagsForLanguageV1::clone_from_borrowed(st)
}),
result.map_project(|st, _| st.into()),
None,
)
}
};
Ok(LocaleExpander {
likely_subtags_l,
likely_subtags_sr,
likely_subtags_ext,
})
}
fn as_borrowed(&self) -> LocaleExpanderBorrowed {
LocaleExpanderBorrowed {
likely_subtags_l: self.likely_subtags_l.get(),
likely_subtags_sr: self.likely_subtags_sr.get(),
likely_subtags_ext: self.likely_subtags_ext.as_ref().map(|p| p.get()),
}
}
/// The maximize method potentially updates a passed in locale in place
/// depending up the results of running the 'Add Likely Subtags' algorithm
/// from <https://www.unicode.org/reports/tr35/#Likely_Subtags>.
///
/// If the result of running the algorithm would result in a new locale, the
/// locale argument is updated in place to match the result, and the method
/// returns [`TransformResult::Modified`]. Otherwise, the method
/// returns [`TransformResult::Unmodified`] and the locale argument is
/// unchanged.
///
/// This function does not guarantee that any particular set of subtags
/// will be present in the resulting locale.
///
/// # Examples
///
/// ```
/// use icu::locid::locale;
/// use icu::locid_transform::{LocaleExpander, TransformResult};
///
/// let lc = LocaleExpander::new();
///
/// let mut locale = locale!("zh-CN");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
/// assert_eq!(locale, locale!("zh-Hans-CN"));
///
/// let mut locale = locale!("zh-Hant-TW");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Unmodified);
/// assert_eq!(locale, locale!("zh-Hant-TW"));
/// ```
///
/// If there is no data for a particular language, the result is not
/// modified. Note that [`LocaleExpander::new_extended`] supports
/// more languages.
///
/// ```
/// use icu::locid::locale;
/// use icu::locid_transform::{LocaleExpander, TransformResult};
///
/// let lc = LocaleExpander::new();
///
/// // No subtags data for ccp in the default set:
/// let mut locale = locale!("ccp");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Unmodified);
/// assert_eq!(locale, locale!("ccp"));
///
/// // The extended set supports it:
/// let lc = LocaleExpander::new_extended();
/// let mut locale = locale!("ccp");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
/// assert_eq!(locale, locale!("ccp-Cakm-BD"));
///
/// // But even the extended set does not support all language subtags:
/// let mut locale = locale!("mul");
/// assert_eq!(lc.maximize(&mut locale), TransformResult::Unmodified);
/// assert_eq!(locale, locale!("mul"));
/// ```
pub fn maximize<T: AsMut<LanguageIdentifier>>(&self, mut langid: T) -> TransformResult {
let langid = langid.as_mut();
let data = self.as_borrowed();
if !langid.language.is_empty() && langid.script.is_some() && langid.region.is_some() {
return TransformResult::Unmodified;
}
if !langid.language.is_empty() {
if let Some(region) = langid.region {
if let Some(script) = data.get_lr(langid.language, region) {
return update_langid(Language::UND, Some(script), None, langid);
}
}
if let Some(script) = langid.script {
if let Some(region) = data.get_ls(langid.language, script) {
return update_langid(Language::UND, None, Some(region), langid);
}
}
if let Some((script, region)) = data.get_l(langid.language) {
return update_langid(Language::UND, Some(script), Some(region), langid);
}
// Language not found: return unmodified.
return TransformResult::Unmodified;
}
if let Some(script) = langid.script {
if let Some(region) = langid.region {
if let Some(language) = data.get_sr(script, region) {
return update_langid(language, None, None, langid);
}
}
if let Some((language, region)) = data.get_s(script) {
return update_langid(language, None, Some(region), langid);
}
}
if let Some(region) = langid.region {
if let Some((language, script)) = data.get_r(region) {
return update_langid(language, Some(script), None, langid);
}
}
// We failed to find anything in the und-SR, und-S, or und-R tables,
// to fall back to bare "und"
debug_assert!(langid.language.is_empty());
update_langid(
data.get_und().0,
Some(data.get_und().1),
Some(data.get_und().2),
langid,
)
}
/// This returns a new Locale that is the result of running the
/// 'Remove Likely Subtags' algorithm from
/// <https://www.unicode.org/reports/tr35/#Likely_Subtags>.
///
/// If the result of running the algorithm would result in a new locale, the
/// locale argument is updated in place to match the result, and the method
/// returns [`TransformResult::Modified`]. Otherwise, the method
/// returns [`TransformResult::Unmodified`] and the locale argument is
/// unchanged.
///
/// # Examples
///
/// ```
/// use icu::locid::locale;
/// use icu::locid_transform::{LocaleExpander, TransformResult};
///
/// let lc = LocaleExpander::new();
///
/// let mut locale = locale!("zh-Hans-CN");
/// assert_eq!(lc.minimize(&mut locale), TransformResult::Modified);
/// assert_eq!(locale, locale!("zh"));
///
/// let mut locale = locale!("zh");
/// assert_eq!(lc.minimize(&mut locale), TransformResult::Unmodified);
/// assert_eq!(locale, locale!("zh"));
/// ```
pub fn minimize<T: AsMut<LanguageIdentifier>>(&self, langid: T) -> TransformResult {
self.minimize_impl(langid, true)
}
/// This returns a new Locale that is the result of running the
/// 'Remove Likely Subtags, favoring script' algorithm from
/// <https://www.unicode.org/reports/tr35/#Likely_Subtags>.
///
/// If the result of running the algorithm would result in a new locale, the
/// locale argument is updated in place to match the result, and the method
/// returns [`TransformResult::Modified`]. Otherwise, the method
/// returns [`TransformResult::Unmodified`] and the locale argument is
/// unchanged.
///
/// # Examples
///
/// ```
/// use icu::locid::locale;
/// use icu::locid_transform::{LocaleExpander, TransformResult};
///
/// let lc = LocaleExpander::new();
///
/// let mut locale = locale!("zh_TW");
/// assert_eq!(
/// lc.minimize_favor_script(&mut locale),
/// TransformResult::Modified
/// );
/// assert_eq!(locale, locale!("zh_Hant"));
/// ```
pub fn minimize_favor_script<T: AsMut<LanguageIdentifier>>(
&self,
langid: T,
) -> TransformResult {
self.minimize_impl(langid, false)
}
fn minimize_impl<T: AsMut<LanguageIdentifier>>(
&self,
mut langid: T,
favor_region: bool,
) -> TransformResult {
let langid = langid.as_mut();
let mut max = langid.clone();
self.maximize(&mut max);
let mut trial = max.clone();
trial.script = None;
trial.region = None;
self.maximize(&mut trial);
if trial == max {
return update_langid_minimize(max.language, None, None, langid);
}
if favor_region {
trial.script = None;
trial.region = max.region;
self.maximize(&mut trial);
if trial == max {
return update_langid_minimize(max.language, None, max.region, langid);
}
trial.script = max.script;
trial.region = None;
self.maximize(&mut trial);
if trial == max {
return update_langid_minimize(max.language, max.script, None, langid);
}
} else {
trial.script = max.script;
trial.region = None;
self.maximize(&mut trial);
if trial == max {
return update_langid_minimize(max.language, max.script, None, langid);
}
trial.script = None;
trial.region = max.region;
self.maximize(&mut trial);
if trial == max {
return update_langid_minimize(max.language, None, max.region, langid);
}
}
update_langid_minimize(max.language, max.script, max.region, langid)
}
// TODO(3492): consider turning this and a future get_likely_region/get_likely_language public
#[inline]
pub(crate) fn get_likely_script<T: AsRef<LanguageIdentifier>>(
&self,
langid: T,
) -> Option<Script> {
let langid = langid.as_ref();
langid
.script
.or_else(|| self.infer_likely_script(langid.language, langid.region))
}
fn infer_likely_script(&self, language: Language, region: Option<Region>) -> Option<Script> {
let data = self.as_borrowed();
// proceed through _all possible cases_ in order of specificity
// (borrowed from LocaleExpander::maximize):
// 1. language + region
// 2. language
// 3. region
// we need to check all cases, because e.g. for "en-US" the default script is associated
// with "en" but not "en-US"
if language != Language::UND {
if let Some(region) = region {
// 1. we know both language and region
if let Some(script) = data.get_lr(language, region) {
return Some(script);
}
}
// 2. we know language, but we either do not know region or knowing region did not help
if let Some((script, _)) = data.get_l(language) {
return Some(script);
}
}
if let Some(region) = region {
// 3. we know region, but we either do not know language or knowing language did not help
if let Some((_, script)) = data.get_r(region) {
return Some(script);
}
}
// we could not figure out the script from the given locale
None
}
}
#[cfg(feature = "serde")]
#[cfg(test)]
mod tests {
use super::*;
use icu_locid::locale;
struct RejectByKeyProvider {
keys: Vec<DataKey>,
}
impl AnyProvider for RejectByKeyProvider {
fn load_any(&self, key: DataKey, _: DataRequest) -> Result<AnyResponse, DataError> {
if self.keys.contains(&key) {
return Err(DataErrorKind::MissingDataKey.with_str_context("rejected"));
}
let l = crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_L_V1;
let ext = crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_EXT_V1;
let sr = crate::provider::Baked::SINGLETON_LOCID_TRANSFORM_LIKELYSUBTAGS_SR_V1;
let payload = if key.hashed() == LikelySubtagsV1Marker::KEY.hashed() {
DataPayload::<LikelySubtagsV1Marker>::from_owned(LikelySubtagsV1 {
language_script: l
.language_script
.iter_copied()
.chain(ext.language_script.iter_copied())
.collect(),
language_region: l
.language_region
.iter_copied()
.chain(ext.language_region.iter_copied())
.collect(),
language: l
.language
.iter_copied()
.chain(ext.language.iter_copied())
.collect(),
script_region: ext.script_region.clone(),
script: ext.script.clone(),
region: ext.region.clone(),
und: l.und,
})
.wrap_into_any_payload()
} else if key.hashed() == LikelySubtagsForLanguageV1Marker::KEY.hashed() {
DataPayload::<LikelySubtagsForLanguageV1Marker>::from_static_ref(l)
.wrap_into_any_payload()
} else if key.hashed() == LikelySubtagsExtendedV1Marker::KEY.hashed() {
DataPayload::<LikelySubtagsExtendedV1Marker>::from_static_ref(ext)
.wrap_into_any_payload()
} else if key.hashed() == LikelySubtagsForScriptRegionV1Marker::KEY.hashed() {
DataPayload::<LikelySubtagsForScriptRegionV1Marker>::from_static_ref(sr)
.wrap_into_any_payload()
} else {
return Err(DataErrorKind::MissingDataKey.into_error());
};
Ok(AnyResponse {
payload: Some(payload),
metadata: Default::default(),
})
}
}
#[test]
fn test_old_keys() {
let provider = RejectByKeyProvider {
keys: vec![
LikelySubtagsForLanguageV1Marker::KEY,
LikelySubtagsForScriptRegionV1Marker::KEY,
LikelySubtagsExtendedV1Marker::KEY,
],
};
let lc = LocaleExpander::try_new_with_any_provider(&provider)
.expect("should create with old keys");
let mut locale = locale!("zh-CN");
assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
assert_eq!(locale, locale!("zh-Hans-CN"));
}
#[test]
fn test_new_keys() {
let provider = RejectByKeyProvider {
keys: vec![LikelySubtagsV1Marker::KEY],
};
let lc = LocaleExpander::try_new_with_any_provider(&provider)
.expect("should create with new keys");
let mut locale = locale!("zh-CN");
assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
assert_eq!(locale, locale!("zh-Hans-CN"));
}
#[test]
fn test_mixed_keys() {
// Include the old key and one of the new keys but not both new keys.
// Not sure if this is a useful test.
let provider = RejectByKeyProvider {
keys: vec![LikelySubtagsForScriptRegionV1Marker::KEY],
};
let lc = LocaleExpander::try_new_with_any_provider(&provider)
.expect("should create with mixed keys");
let mut locale = locale!("zh-CN");
assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
assert_eq!(locale, locale!("zh-Hans-CN"));
}
#[test]
fn test_no_keys() {
let provider = RejectByKeyProvider {
keys: vec![
LikelySubtagsForLanguageV1Marker::KEY,
LikelySubtagsForScriptRegionV1Marker::KEY,
LikelySubtagsV1Marker::KEY,
],
};
if LocaleExpander::try_new_with_any_provider(&provider).is_ok() {
panic!("should not create: no data present")
};
}
#[test]
fn test_new_small_keys() {
// Include the new small keys but not the extended key
let provider = RejectByKeyProvider {
keys: vec![
LikelySubtagsExtendedV1Marker::KEY,
LikelySubtagsV1Marker::KEY,
],
};
let lc = LocaleExpander::try_new_with_any_provider(&provider)
.expect("should create with mixed keys");
let mut locale = locale!("zh-CN");
assert_eq!(lc.maximize(&mut locale), TransformResult::Modified);
assert_eq!(locale, locale!("zh-Hans-CN"));
}
#[test]
fn test_minimize_favor_script() {
let lc = LocaleExpander::new();
let mut locale = locale!("yue-Hans");
assert_eq!(
lc.minimize_favor_script(&mut locale),
TransformResult::Unmodified
);
assert_eq!(locale, locale!("yue-Hans"));
}
#[test]
fn test_minimize_favor_region() {
let lc = LocaleExpander::new();
let mut locale = locale!("yue-Hans");
assert_eq!(lc.minimize(&mut locale), TransformResult::Modified);
assert_eq!(locale, locale!("yue-CN"));
}
}