diff --git a/src/lang.rs b/src/lang.rs index e9ee151..97fb56f 100644 --- a/src/lang.rs +++ b/src/lang.rs @@ -221,6 +221,8 @@ fn success_parse_unicode_language_id() { assert_eq!(Some("Latn".to_string()), result.script); assert_eq!(Some("US".to_string()), result.region); assert_eq!(Some(vec!["macos".to_string()]), result.variants); + let result: UnicodeLanguageIdentifier = "en-Latn-US".parse().unwrap(); + assert_eq!("en-Latn-US", format!("{}", result)); } #[test] diff --git a/src/locale.rs b/src/locale.rs index 0442de2..8f550ec 100644 --- a/src/locale.rs +++ b/src/locale.rs @@ -1,10 +1,12 @@ use crate::constants::SEP; use crate::errors::ParserError; -use crate::extensions::{parse_extensions_from_iter, Extensions}; +use crate::extensions::{self, parse_extensions_from_iter, Extensions}; use crate::lang::{parse_unicode_language_id_from_iter, UnicodeLanguageIdentifier}; use crate::shared::split_str; use std::fmt::{self}; +use std::str; +use std::str::FromStr; #[derive(Debug)] pub struct UnicodeLocaleIdentifier { @@ -14,14 +16,25 @@ pub struct UnicodeLocaleIdentifier { impl fmt::Display for UnicodeLocaleIdentifier { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut messages = vec![]; - messages.push(format!("{}", self.language)); - messages.push(format!("{}", self.extensions)); - f.write_str(&messages.join(&SEP.to_string()))?; + let mut msg = vec![]; + msg.push(format!("{}", self.language)); + let extensions_msg = format!("{}", self.extensions); + if !extensions_msg.is_empty() { + msg.push(extensions_msg); + } + f.write_str(&msg.join(&SEP.to_string()))?; Ok(()) } } +impl FromStr for UnicodeLocaleIdentifier { + type Err = ParserError; + + fn from_str(source: &str) -> Result { + parse_unicode_locale_id(source) + } +} + pub fn parse_unicode_locale_id(locale: &str) -> Result { // check empty if locale.is_empty() { @@ -59,6 +72,10 @@ fn success_parse_unicode_locale_id() { format!("{}", parse_unicode_locale_id("ja-Latn-JP-macos-U-attr1-kz-value2-t-en-Latn-US-linux-t1-value1-value2-a-vue-rust-x-foo-123") .unwrap()) ); + + // FromStr trait implementation + let result: UnicodeLocaleIdentifier = "ja-Latn-JP".parse().unwrap(); + assert_eq!("ja-Latn-JP", format!("{}", result)); } #[test]