Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example for icu_locale #250

Merged
merged 4 commits into from
Sep 22, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions components/locale/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,7 @@ harness = false
[[bench]]
name = "locale"
harness = false

[[example]]
name = "filter_langids"
test = true
55 changes: 55 additions & 0 deletions components/locale/examples/filter_langids.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// A sample application which takes a comma separated list of language identifiers,
// filters out identifiers with language subtags different than `en` and serializes
// the list back into a comma separated list in canonical syntax.
use std::env;

use icu_locale::{subtags, LanguageIdentifier};

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: Vec<LanguageIdentifier> = input
.split(',')
.filter_map(|s| s.trim().parse().ok())
.collect();

// 2. Filter for LanguageIdentifiers with Language subtag `en`.
let en_lang: subtags::Language = "en".parse().expect("Failed to parse language subtag.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a good place to demo the macros?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

once we land them, I'll switch to them in examples :)


let en_langids = langids
.into_iter()
.filter(|langid| langid.language == en_lang);

// 3. Serialize the output.
let en_strs: Vec<String> = en_langids.map(|langid| langid.to_string()).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);

#[cfg(debug_assertions)]
println!("\nInput: {}\nOutput: {}", input, _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);
}
}