tina-core 0.0.2

Tina platform
Documentation
//! 国际化字符串
use crate::tina::i18n::ResourceBundle;
use std::fmt::Display;

/// 国际化字符串
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct I18nString {
    direct: bool,
    key: String,
    args: Vec<(String, String)>,
}

impl I18nString {
    /// 从一个key构造
    pub fn from_key(key: impl Display) -> I18nString {
        I18nString {
            direct: false,
            key: format!("{}", key),
            args: vec![],
        }
    }

    /// 从一个key和参数构造, 参数的模板格式为 {$0}, {$1}, {$2}...这些
    pub fn from_key_args(key: impl Display, args: Vec<impl Display>) -> I18nString {
        let mut new_args: Vec<(String, String)> = Vec::with_capacity(args.len());
        let mut idx = -1;
        for arg in args.into_iter() {
            idx += 1;
            new_args.push((idx.to_string(), format!("{}", arg)));
        }
        I18nString {
            direct: false,
            key: format!("{}", key),
            args: new_args,
        }
    }

    /// 从一个key和参数构造, 参数的模板格式为任意的 {..} 格式
    pub fn from(key: impl Display, args: Vec<(impl Display, impl Display)>) -> I18nString {
        I18nString {
            direct: false,
            key: format!("{}", key),
            args: args.into_iter().map(|(key, value)| (format!("{}", key), format!("{}", value))).collect(),
        }
    }

    /// 构造一个不带国际化翻译的字符串
    pub fn direct_from(str: impl Display) -> I18nString {
        I18nString {
            direct: true,
            key: format!("{}", str),
            args: vec![],
        }
    }

    /// 构造一个不带国际化翻译的字符串
    pub fn direct_from_string(str: String) -> I18nString {
        I18nString {
            direct: true,
            key: str,
            args: vec![],
        }
    }

    /// 添加参数
    pub fn add_arg(&mut self, name: impl Display, value: impl Display) -> &mut Self {
        self.args.push((format!("{}", name), format!("{}", value)));
        self
    }

    /// 读取翻译后的字符串结果
    pub fn get_string(&self, locale: &str) -> String {
        if self.direct {
            return self.key.to_string();
        }
        ResourceBundle::get_string_by_key_args(
            locale,
            &self.key,
            self.args.iter().map(|(key, value)| (key.as_str(), value.as_str())).collect(),
        )
    }
}

impl PartialEq for I18nString {
    fn eq(&self, other: &Self) -> bool {
        let locale = ResourceBundle::get_default_locale();
        self.get_string(locale.as_str()) == other.get_string(locale.as_str())
    }
}