#![warn(missing_docs)]
use std::{error::Error, fmt::Display};
#[cfg(any(target_os = "android", target_arch = "wasm32"))]
compile_error!("You are compiling for an unimplemented platform!\nContributions are welcome to current_locale to implement any new platforms.");
#[cfg(target_os = "windows")]
#[path = "windows.rs"]
mod imp;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[path = "apple.rs"]
mod imp;
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "android"))
))]
#[path = "unix.rs"]
mod imp;
pub fn current_locale() -> Result<String, LocaleError> {
imp::current_locale()
}
#[derive(Debug)]
pub struct LocaleError {
kind: ErrorKind,
description: Option<String>,
}
impl LocaleError {
pub fn kind(self) -> ErrorKind {
self.kind
}
}
impl Display for LocaleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(description) = &self.description {
write!(f, "{}: {}", self.kind, description)
} else {
Display::fmt(&self.kind, f)
}
}
}
impl Error for LocaleError {}
#[derive(Debug)]
pub enum ErrorKind {
NotIetfCompliant(String),
LookupFailed,
}
impl Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
ErrorKind::NotIetfCompliant(_) => "locale code returned is not ietf compliant",
ErrorKind::LookupFailed => "getting locale from system failed",
}
)
}
}
impl Error for ErrorKind {}
impl From<ErrorKind> for LocaleError {
fn from(kind: ErrorKind) -> Self {
LocaleError {
kind,
description: None,
}
}
}
#[cfg(test)]
mod test {
use crate::{current_locale, ErrorKind};
#[test]
fn parse_runtime_locale() {
let locale = current_locale();
match locale {
Ok(locale) => println!("Got locale code {}", locale),
Err(error) => match error.kind() {
ErrorKind::NotIetfCompliant(s) => {
panic!("Got locale code {} but it is not IETF compliant!", s)
}
ErrorKind::LookupFailed => panic!("Failed to look up locale code from the OS!"),
},
}
}
}