cjtoolkit_structured_validator/common/
locale.rs

1//! This module contains structures and traits for working with locales and localization.
2
3pub use crate::common::validation_collector::{ValidateErrorCollector, ValidateErrorStore};
4use std::collections::HashMap;
5use std::sync::Arc;
6
7/// Represents various types of values associated with a locale.
8///
9/// `LocaleValue` is an enum that allows for storage and handling of multiple data types.
10/// This can be useful in scenarios where locale-specific values need to support different kinds of data.
11///
12/// Variants:
13/// - `String(String)`: Stores a UTF-8 encoded string value.
14/// - `Uint(usize)`: Stores an unsigned integer value.
15/// - `Int(isize)`: Stores a signed integer value.
16/// - `Float(f64)`: Stores a floating-point number value.
17///
18/// The `Clone` trait is implemented for `LocaleValue`, allowing instances of this enum to be duplicated.
19///
20/// Example:
21/// ```
22/// use cjtoolkit_structured_validator::common::locale::LocaleValue;
23/// let string_locale = LocaleValue::String(String::from("Hello"));
24/// let unsigned_locale = LocaleValue::Uint(42);
25/// let signed_locale = LocaleValue::Int(-7);
26/// let float_locale = LocaleValue::Float(3.14);
27///
28/// match string_locale {
29///     LocaleValue::String(s) => println!("String value: {}", s),
30///     _ => println!("Not a string"),
31/// }
32/// ```
33#[derive(Clone)]
34pub enum LocaleValue {
35    String(String),
36    Uint(usize),
37    Int(isize),
38    Float(f64),
39}
40
41impl From<String> for LocaleValue {
42    fn from(s: String) -> Self {
43        Self::String(s)
44    }
45}
46
47impl From<&str> for LocaleValue {
48    fn from(s: &str) -> Self {
49        Self::String(s.to_string())
50    }
51}
52
53impl From<usize> for LocaleValue {
54    fn from(s: usize) -> Self {
55        Self::Uint(s)
56    }
57}
58
59impl From<isize> for LocaleValue {
60    fn from(s: isize) -> Self {
61        Self::Int(s)
62    }
63}
64
65impl From<f64> for LocaleValue {
66    fn from(s: f64) -> Self {
67        Self::Float(s)
68    }
69}
70
71/**
72 * Represents the localization data for a specific locale.
73 * This structure holds locale-specific information, such as the locale's name
74 * and associated arguments or values used for localization.
75 */
76pub struct LocaleData {
77    pub name: String,
78    pub args: HashMap<String, LocaleValue>,
79}
80
81impl LocaleData {
82    /// Creates a new instance of the struct with the provided name.
83    ///
84    /// # Parameters
85    /// - `name`: A string slice that represents the name to associate with the instance.
86    ///
87    /// # Returns
88    /// A new instance of the struct, where the `name` field is initialized
89    /// with the provided value and the `args` field is set to its default value.
90    ///
91    /// # Example
92    /// ```
93    /// use cjtoolkit_structured_validator::common::locale::LocaleData;
94    /// let instance = LocaleData::new("example");
95    /// ```
96    pub fn new(name: &str) -> Arc<Self> {
97        Arc::new(Self {
98            name: name.to_string(),
99            args: Default::default(),
100        })
101    }
102
103    /// Creates a new instance of the structure using a name and a vector of key-value pairs.
104    ///
105    /// # Arguments
106    ///
107    /// * `name` - A string slice representing the name for the new instance.
108    /// * `args` - A vector containing tuples, where each tuple consists of a `String` (key)
109    ///   and a `LocaleValue` (value). These key-value pairs will be used to initialize
110    ///   the args map of the structure.
111    ///
112    /// # Returns
113    ///
114    /// A new instance of the structure is populated with the provided `name` and `args`.
115    ///
116    /// # Example
117    ///
118    /// ```rust
119    /// use cjtoolkit_structured_validator::common::locale::LocaleData;
120    /// use cjtoolkit_structured_validator::common::locale::LocaleValue;
121    /// let instance = LocaleData::new_with_vec("example_name", vec![
122    ///     ("key1".to_string(), LocaleValue::from("value1")),
123    ///     ("key2".to_string(), LocaleValue::from("value2")),
124    /// ]);
125    /// assert_eq!(instance.name, "example_name");
126    /// assert!(instance.args.contains_key("key1"));
127    /// ```
128    pub fn new_with_vec(name: &str, args: Vec<(String, LocaleValue)>) -> Arc<Self> {
129        Arc::new(Self {
130            name: name.to_string(),
131            args: args.into_iter().collect(),
132        })
133    }
134}
135
136/// A trait representing a localized message provider that offers locale-specific data.
137///
138/// Types that implement this trait are expected to provide a mechanism for retrieving
139/// locale-specific data useful for internationalization or localization purposes. Implementers must
140/// be `Send` and `Sync` to ensure safe usage in concurrent environments.
141///
142/// # Required Methods
143///
144/// - `get_locale_data`: Retrieves locale-specific information encapsulated in a `LocaleData` object.
145///
146/// # Example
147///
148/// ```rust
149/// use std::sync::Arc;
150/// use cjtoolkit_structured_validator::common::locale::{LocaleMessage, LocaleData};
151///
152/// struct MyLocaleMessage;
153///
154/// impl LocaleMessage for MyLocaleMessage {
155///     fn get_locale_data(&self) -> Arc<LocaleData> {
156///         LocaleData::new("validate-example")
157///     }
158/// }
159///
160/// let locale_message = MyLocaleMessage;
161/// let locale_data = locale_message.get_locale_data();
162/// ```
163///
164/// # Notes
165///
166/// This trait is designed to be used in scenarios where thread-safe and cross-thread access
167/// to locale information is necessary.
168pub trait LocaleMessage: Send + Sync {
169    fn get_locale_data(&self) -> Arc<LocaleData>;
170}
171
172impl LocaleMessage for Arc<LocaleData> {
173    fn get_locale_data(&self) -> Arc<LocaleData> {
174        Arc::clone(self)
175    }
176}