Skip to content

Commit

Permalink
Improve examples (#5224)
Browse files Browse the repository at this point in the history
This gets rid of some allocations (like vecs), which we don't want to
affect the memory benchmarks.
  • Loading branch information
robertbastian authored Jul 11, 2024
1 parent edf9938 commit 747b31a
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 166 deletions.
22 changes: 6 additions & 16 deletions components/calendar/examples/iso_date_manipulations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -27,24 +27,14 @@ const DATES_ISO: &[(i32, u8, u8)] = &[
(2033, 6, 10),
];

fn tuple_to_iso_date(date: (i32, u8, u8)) -> Result<Date<Iso>, 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::<Result<Vec<Date<Iso>>, _>>()
.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,
);
}
}
29 changes: 10 additions & 19 deletions components/calendar/examples/iso_datetime_manipulations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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<DateTime<Iso>, 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::<Result<Vec<DateTime<Iso>>, _>>()
.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),
);
}
}
49 changes: 21 additions & 28 deletions components/collections/examples/unicode_bmp_blocks_selector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -37,17 +26,26 @@ enum BmpBlock {
Unknown,
}

struct BmpBlockSelector<'data> {
blocks: Vec<(BmpBlock, CodePointInversionList<'data>)>,
const BLOCKS: [(BmpBlock, RangeInclusive<char>); 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 {
Expand All @@ -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:#?}");
}
}
21 changes: 7 additions & 14 deletions components/datetime/examples/work_log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Result<Vec<DateTime<Gregorian>>, _>>()
.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::<Gregorian>::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);
}
}
56 changes: 17 additions & 39 deletions components/locale_core/examples/filter_langids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = en_langids
.map(|langid| langid.write_to_string().into_owned())
.collect();

en_strs.join(", ")
}

fn main() {
let args: Vec<String> = 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)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = input
.split(',')
.filter_map(|s| Locale::canonicalize(s.trim()).ok())
.collect();

canonical_locales.join(", ")
}

fn main() {
let args: Vec<String> = 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}");
}
}
12 changes: 4 additions & 8 deletions utils/litemap/examples/language_names_hash_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Language, &str>::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")));
}
12 changes: 4 additions & 8 deletions utils/litemap/examples/language_names_lite_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Language, &str>::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());
}

0 comments on commit 747b31a

Please sign in to comment.