diff --git a/components/calendar/examples/iso_date_manipulations.rs b/components/calendar/examples/iso_date_manipulations.rs index f4f8e94883a..5b5f1d39d9d 100644 --- a/components/calendar/examples/iso_date_manipulations.rs +++ b/components/calendar/examples/iso_date_manipulations.rs @@ -9,7 +9,7 @@ icu_benchmark_macros::instrument!(); use icu_benchmark_macros::println; -use icu_calendar::{Date, Iso, RangeError}; +use icu_calendar::Date; const DATES_ISO: &[(i32, u8, u8)] = &[ (1970, 1, 1), @@ -27,24 +27,14 @@ const DATES_ISO: &[(i32, u8, u8)] = &[ (2033, 6, 10), ]; -fn tuple_to_iso_date(date: (i32, u8, u8)) -> Result, RangeError> { - Date::try_new_iso_date(date.0, date.1, date.2) -} - fn main() { - let dates = DATES_ISO - .iter() - .copied() - .map(tuple_to_iso_date) - .collect::>, _>>() - .expect("Failed to parse dates."); - - for date_input in dates { + for &(year, month, day) in DATES_ISO { + let date = Date::try_new_iso_date(year, month, day).expect("date should parse"); println!( "Year: {}, Month: {}, Day: {}", - date_input.year().number, - date_input.month().ordinal, - date_input.day_of_month().0, + date.year().number, + date.month().ordinal, + date.day_of_month().0, ); } } diff --git a/components/calendar/examples/iso_datetime_manipulations.rs b/components/calendar/examples/iso_datetime_manipulations.rs index 1c8c9a041b9..4edbe681a62 100644 --- a/components/calendar/examples/iso_datetime_manipulations.rs +++ b/components/calendar/examples/iso_datetime_manipulations.rs @@ -9,7 +9,7 @@ icu_benchmark_macros::instrument!(); use icu_benchmark_macros::println; -use icu_calendar::{DateError, DateTime, Iso}; +use icu_calendar::DateTime; const DATETIMES_ISO: &[(i32, u8, u8, u8, u8, u8)] = &[ (1970, 1, 1, 3, 5, 12), @@ -27,27 +27,18 @@ const DATETIMES_ISO: &[(i32, u8, u8, u8, u8, u8)] = &[ (2033, 6, 10, 17, 22, 22), ]; -fn tuple_to_iso_datetime(date: (i32, u8, u8, u8, u8, u8)) -> Result, DateError> { - DateTime::try_new_iso_datetime(date.0, date.1, date.2, date.3, date.4, date.5) -} - fn main() { - let datetimes = DATETIMES_ISO - .iter() - .copied() - .map(tuple_to_iso_datetime) - .collect::>, _>>() - .expect("Failed to parse datetimes."); - - for datetime_input in datetimes { + for &(year, month, day, hour, minute, second) in DATETIMES_ISO { + let datetime = DateTime::try_new_iso_datetime(year, month, day, hour, minute, second) + .expect("datetime should parse"); println!( "Year: {}, Month: {}, Day: {}, Hour: {}, Minute: {}, Second: {}", - datetime_input.date.year().number, - datetime_input.date.month().ordinal, - datetime_input.date.day_of_month().0, - u8::from(datetime_input.time.hour), - u8::from(datetime_input.time.minute), - u8::from(datetime_input.time.second), + datetime.date.year().number, + datetime.date.month().ordinal, + datetime.date.day_of_month().0, + u8::from(datetime.time.hour), + u8::from(datetime.time.minute), + u8::from(datetime.time.second), ); } } diff --git a/components/collections/examples/unicode_bmp_blocks_selector.rs b/components/collections/examples/unicode_bmp_blocks_selector.rs index 0333dade0b8..c29f1d25000 100644 --- a/components/collections/examples/unicode_bmp_blocks_selector.rs +++ b/components/collections/examples/unicode_bmp_blocks_selector.rs @@ -17,18 +17,7 @@ icu_benchmark_macros::instrument!(); use icu_benchmark_macros::println; use icu_collections::codepointinvlist::{CodePointInversionList, CodePointInversionListBuilder}; - -fn get_basic_latin_block() -> CodePointInversionList<'static> { - let mut builder = CodePointInversionListBuilder::new(); - builder.add_range('\u{0000}'..='\u{007F}'); - builder.build() -} - -fn get_latin1_supplement_block() -> CodePointInversionList<'static> { - let mut builder = CodePointInversionListBuilder::new(); - builder.add_range('\u{0080}'..='\u{00FF}'); - builder.build() -} +use std::ops::RangeInclusive; #[derive(Copy, Clone, Debug)] enum BmpBlock { @@ -37,17 +26,26 @@ enum BmpBlock { Unknown, } -struct BmpBlockSelector<'data> { - blocks: Vec<(BmpBlock, CodePointInversionList<'data>)>, +const BLOCKS: [(BmpBlock, RangeInclusive); 2] = [ + (BmpBlock::Basic, '\u{0000}'..='\u{007F}'), + (BmpBlock::Latin1Supplement, '\u{0080}'..='\u{00FF}'), +]; + +struct BmpBlockSelector { + blocks: [(BmpBlock, CodePointInversionList<'static>); 2], } -impl<'data> BmpBlockSelector<'data> { - pub fn new() -> Self { - let blocks = vec![ - (BmpBlock::Basic, get_basic_latin_block()), - (BmpBlock::Latin1Supplement, get_latin1_supplement_block()), - ]; - BmpBlockSelector { blocks } +impl BmpBlockSelector { + pub fn new() -> BmpBlockSelector { + BmpBlockSelector { + blocks: BLOCKS.map(|(ch, range)| { + (ch, { + let mut builder = CodePointInversionListBuilder::new(); + builder.add_range(range); + builder.build() + }) + }), + } } pub fn select(&self, input: char) -> BmpBlock { @@ -65,14 +63,9 @@ fn main() { let sample = "Welcome to MyName©®, Алексей!"; - let mut result = vec![]; - - for ch in sample.chars() { - result.push((ch, selector.select(ch))); - } - println!("\n====== Unicode BMP Block Selector example ============"); - for (ch, block) in result { + for ch in sample.chars() { + let block = selector.select(ch); println!("{ch}: {block:#?}"); } } diff --git a/components/datetime/examples/work_log.rs b/components/datetime/examples/work_log.rs index 8b2efbf82d5..bc3a091aa67 100644 --- a/components/datetime/examples/work_log.rs +++ b/components/datetime/examples/work_log.rs @@ -27,26 +27,19 @@ const DATES_ISO: &[(i32, u8, u8, u8, u8, u8)] = &[ ]; fn main() { - let dates = DATES_ISO - .iter() - .copied() - .map(|(y, m, d, h, min, s)| DateTime::try_new_gregorian_datetime(y, m, d, h, min, s)) - .collect::>, _>>() - .expect("Failed to parse dates."); - let mut options = length::Bag::default(); - options.date = Some(length::Date::Medium); options.time = Some(length::Time::Short); let dtf = TypedDateTimeFormatter::::try_new(&locale!("en").into(), options.into()) .expect("Failed to create TypedDateTimeFormatter instance."); - { - println!("\n====== Work Log (en) example ============"); - for (idx, date) in dates.iter().enumerate() { - let fdt = dtf.format(date); - println!("{idx}) {fdt}"); - } + println!("\n====== Work Log (en) example ============"); + + for (idx, &(year, month, day, hour, minute, second)) in DATES_ISO.iter().enumerate() { + let date = DateTime::try_new_gregorian_datetime(year, month, day, hour, minute, second) + .expect("datetime should parse"); + let fdt = dtf.format(&date); + println!("{idx}) {}", fdt); } } diff --git a/components/locale_core/examples/filter_langids.rs b/components/locale_core/examples/filter_langids.rs index 18dbeaf4c90..f990903f885 100644 --- a/components/locale_core/examples/filter_langids.rs +++ b/components/locale_core/examples/filter_langids.rs @@ -16,49 +16,27 @@ use icu_benchmark_macros::println; use std::env; use icu_locale_core::{subtags, LanguageIdentifier}; -use writeable::Writeable; const DEFAULT_INPUT: &str = "de, en-us, zh-hant, sr-cyrl, fr-ca, es-cl, pl, en-latn-us, ca-valencia, und-arab"; -fn filter_input(input: &str) -> String { - // 1. Parse the input string into a list of language identifiers. - let langids = input.split(',').filter_map(|s| s.trim().parse().ok()); - - // 2. Filter for LanguageIdentifiers with Language subtag `en`. - let en_lang: subtags::Language = "en".parse().expect("Failed to parse language subtag."); - - let en_langids = langids.filter(|langid: &LanguageIdentifier| langid.language == en_lang); - - // 3. Serialize the output. - let en_strs: Vec = en_langids - .map(|langid| langid.write_to_string().into_owned()) - .collect(); - - en_strs.join(", ") -} - fn main() { - let args: Vec = env::args().collect(); - - let input = if let Some(input) = args.get(1) { - input.as_str() - } else { - DEFAULT_INPUT - }; - let _output = filter_input(input); - - println!("\nInput: {input}\nOutput: {_output}"); -} - -#[cfg(test)] -mod tests { - use super::*; - - const DEFAULT_OUTPUT: &str = "en-US, en-Latn-US"; - - #[test] - fn ensure_default_output() { - assert_eq!(filter_input(DEFAULT_INPUT), DEFAULT_OUTPUT); + for input in env::args() + .nth(1) + .as_deref() + .unwrap_or(DEFAULT_INPUT) + .split(',') + .map(str::trim) + { + // 1. Parse the input string into a language identifier. + let Ok(langid) = LanguageIdentifier::try_from_str(input) else { + continue; + }; + // 2. Filter for LanguageIdentifiers with Language subtag `en`. + if langid.language == subtags::language!("en") { + println!("✅ {}", langid) + } else { + println!("❌ {}", langid) + } } } diff --git a/components/locale_core/examples/syntatically_canonicalize_locales.rs b/components/locale_core/examples/syntatically_canonicalize_locales.rs index fc03d275857..104d43402c7 100644 --- a/components/locale_core/examples/syntatically_canonicalize_locales.rs +++ b/components/locale_core/examples/syntatically_canonicalize_locales.rs @@ -15,40 +15,15 @@ use icu_locale_core::Locale; const DEFAULT_INPUT: &str = "sr-cyrL-rS, es-mx, und-arab-u-ca-Buddhist"; -fn syntactically_canonicalize_locales(input: &str) -> String { - // Split input string and canonicalize each locale identifier. - let canonical_locales: Vec = input - .split(',') - .filter_map(|s| Locale::canonicalize(s.trim()).ok()) - .collect(); - - canonical_locales.join(", ") -} - fn main() { - let args: Vec = env::args().collect(); - - let input = if let Some(input) = args.get(1) { - input.as_str() - } else { - DEFAULT_INPUT - }; - let _output = syntactically_canonicalize_locales(input); - - println!("\nInput: {input}\nOutput: {_output}"); -} - -#[cfg(test)] -mod tests { - use super::*; - - const DEFAULT_OUTPUT: &str = "sr-Cyrl-RS, es-MX, und-Arab-u-ca-buddhist"; - - #[test] - fn ensure_default_output() { - assert_eq!( - syntactically_canonicalize_locales(DEFAULT_INPUT), - DEFAULT_OUTPUT - ); + for input in env::args() + .nth(1) + .as_deref() + .unwrap_or(DEFAULT_INPUT) + .split(',') + .map(str::trim) + { + let output = Locale::canonicalize(input).unwrap(); + println!("{input} -> {output}"); } } diff --git a/utils/litemap/examples/language_names_hash_map.rs b/utils/litemap/examples/language_names_hash_map.rs index 526e3057eef..6e3566b134a 100644 --- a/utils/litemap/examples/language_names_hash_map.rs +++ b/utils/litemap/examples/language_names_hash_map.rs @@ -28,13 +28,9 @@ const DATA: [(Language, &str); 11] = [ ]; fn main() { - let mut map = HashMap::new(); - // https://github.com/rust-lang/rust/issues/62633 was declined :( - for (lang, name) in DATA.iter() { - map.insert(lang, name).ok_or(()).unwrap_err(); - } + let map = HashMap::::from_iter(DATA); - assert_eq!(11, map.len()); - assert_eq!(Some(&&"Thai"), map.get(&language!("th"))); - assert_eq!(None, map.get(&language!("de"))); + assert!(map.len() == 11); + assert!(map.get(&language!("th")) == Some(&"Thai")); + assert!(!map.contains_key(&language!("de"))); } diff --git a/utils/litemap/examples/language_names_lite_map.rs b/utils/litemap/examples/language_names_lite_map.rs index 57b59e31a76..83bff93dfd3 100644 --- a/utils/litemap/examples/language_names_lite_map.rs +++ b/utils/litemap/examples/language_names_lite_map.rs @@ -28,13 +28,9 @@ const DATA: [(Language, &str); 11] = [ ]; fn main() { - let mut map = LiteMap::new_vec(); - // https://github.com/rust-lang/rust/issues/62633 was declined :( - for (lang, name) in DATA.iter() { - map.try_append(lang, name).ok_or(()).unwrap_err(); - } + let map = LiteMap::::from_iter(DATA); - assert_eq!(11, map.len()); - assert_eq!(Some(&&"Thai"), map.get(&language!("th"))); - assert_eq!(None, map.get(&language!("de"))); + assert!(map.len() == 11); + assert!(map.get(&language!("th")) == Some(&"Thai")); + assert!(map.get(&language!("de")).is_none()); }