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

Provide a new API that returns the vector of available ICU locales us… #292

Merged
merged 3 commits into from
Oct 30, 2023
Merged
Changes from all 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
36 changes: 35 additions & 1 deletion rust_icu_uloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use {
convert::{From, TryFrom, TryInto},
ffi, fmt,
os::raw,
sync::OnceLock,
},
};

Expand All @@ -37,7 +38,7 @@ const LOCALE_CAPACITY: usize = 158;
/// [ULocMut] is a mutable companion to [ULoc].
///
/// It has methods that allow one to create a different [ULoc] by adding and
/// removing keywords to the locale identifier. You can only creates a `ULocMut`
/// removing keywords to the locale identifier. You can only create a `ULocMut`
/// by converting from an existing `ULoc` by calling `ULocMut::from`. And once
/// you are done changing it, you can only convert it back with `ULoc::from`.
///
Expand Down Expand Up @@ -361,6 +362,29 @@ impl ULoc {
)
}

/// Implements `uloc_countAvailable`.
pub fn count_available() -> i32 {
let count = unsafe { versioned_function!(uloc_countAvailable)() };
count
}

/// Implements `uloc_getAvailable`.
pub fn get_available() -> &'static Vec<ULoc> {
static LOCALES: OnceLock<Vec<ULoc>> = OnceLock::new();
LOCALES.get_or_init(|| {
let count = ULoc::count_available();
let mut vec = Vec::with_capacity(count as usize);
let mut index: i32 = 0;
while index < count {
let label = unsafe { ffi::CStr::from_ptr(versioned_function!(uloc_getAvailable)(index)).to_str().unwrap() };
let locale = ULoc::try_from(label).unwrap();
vec.push(locale);
index += 1;
}
vec
})
}

/// Implements `uloc_addLikelySubtags` from ICU4C.
pub fn add_likely_subtags(&self) -> Result<ULoc, common::Error> {
self.call_buffered_string_method(versioned_function!(uloc_addLikelySubtags))
Expand Down Expand Up @@ -1244,4 +1268,14 @@ mod tests {
"azerbaïdjanais (cyrillique, Azerbaïdjan, calendrier=calendrier hébraïque, t=it, usage privé=whatever)"
);
}
#[test]
fn test_get_available() {
let locales = ULoc::get_available();
assert!(locales.contains(&ULoc::try_from("en").unwrap()));
assert!(locales.contains(&ULoc::try_from("en-US").unwrap()));
assert!(locales.contains(&ULoc::try_from("fr").unwrap()));
assert!(locales.contains(&ULoc::try_from("fr-FR").unwrap()));
assert_eq!(ULoc::count_available() as usize, locales.capacity());
assert_eq!(locales.len(), locales.capacity());
}
}
Loading