rust_intl 0.2.1

A Rust internationalization library
Documentation
//! Optional global "current locale".
//!
//! This file is used by the [`get_current_locale!`] and [`set_current_locale!`] macros
//! generated by `load!()`. Meant for single-user apps (desktop, CLI, ...)
//! where only one locale is active at a time.

use std::any::Any;
use std::sync::{OnceLock, RwLock};

static CURRENT: OnceLock<RwLock<Box<dyn Any + Send + Sync>>> = OnceLock::new();

/// Stores `locale` as the global current locale.
///
/// Safe to call from any thread.
#[doc(hidden)]
pub fn set_current_locale<L: Copy + Send + Sync + 'static>(locale: L) {
    let lock = CURRENT.get_or_init(|| RwLock::new(Box::new(locale)));
    *lock.write().unwrap() = Box::new(locale);
}

/// Returns the locale stored with [`set_current_locale`], or
/// `L::default()` if none has been set.
#[doc(hidden)]
pub fn get_current_locale<L: Copy + Send + Sync + Default + 'static>() -> L {
    match CURRENT.get() {
        Some(lock) => *lock.read().unwrap().downcast_ref::<L>().expect(
            "rust_intl: get_current_locale::<L>() called with a different \
             locale type than set_current_locale() was called with",
        ),
        None => L::default(),
    }
}