Skip to content

Commit

Permalink
fix: FromStr trait implementaion for UnicodeLocaleIdentifier
Browse files Browse the repository at this point in the history
  • Loading branch information
kazupon committed Jan 8, 2024
1 parent 82ff4c6 commit 78aa0bd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/lang.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
27 changes: 22 additions & 5 deletions src/locale.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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<Self, Self::Err> {
parse_unicode_locale_id(source)
}
}

pub fn parse_unicode_locale_id(locale: &str) -> Result<UnicodeLocaleIdentifier, ParserError> {
// check empty
if locale.is_empty() {
Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit 78aa0bd

Please sign in to comment.