Skip to main content

qubit_value/
named_value.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Named Single Value
10//!
11//! Provides a named container for single values, allowing readable identifiers
12//! to be added to individual values in complex configurations or structures.
13//!
14//! Suitable for scenarios such as log annotation, configuration item encapsulation,
15//! and preserving strongly typed values in key-value pairs.
16//!
17//! # Author
18//!
19//! Haixing Hu
20
21use serde::{Deserialize, Serialize};
22use std::ops::{Deref, DerefMut};
23
24use super::value::Value;
25
26/// Named single value
27///
28/// Associates a human-readable name with a single [`Value`], facilitating identification,
29/// retrieval, and display in configurations, parameter passing, and complex data structures.
30///
31/// # Features
32///
33/// - Provides stable name identification for values
34/// - Automatically dereferences to the inner [`Value`] via `Deref`, allowing direct access to [`Value`] methods
35/// - Supports `serde` serialization and deserialization
36///
37/// # Use Cases
38///
39/// - Configuration item encapsulation (e.g., `"port"`, `"timeout"`, etc.)
40/// - Named output of key values in logs/monitoring
41/// - Quick location by name in collections
42///
43/// # Example
44///
45/// ```rust
46/// use common_rs::util::value::{NamedValue, Value};
47///
48/// let named = NamedValue::new("flag", Value::Bool(true));
49/// // Call Value methods through Deref
50/// assert_eq!(named.to::<bool>().unwrap(), true);
51/// ```
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct NamedValue {
54    /// Name of the value
55    name: String,
56    /// Content of the value
57    value: Value,
58}
59
60impl NamedValue {
61    /// Create a new named value
62    ///
63    /// Creates a binding instance between a name and a value.
64    ///
65    /// # Parameters
66    ///
67    /// * `name` - Name of the value
68    /// * `value` - Content of the value
69    ///
70    /// # Returns
71    ///
72    /// Returns a newly created [`NamedValue`] instance
73    ///
74    /// # Example
75    ///
76    /// ```rust
77    /// use common_rs::util::value::{NamedValue, Value};
78    ///
79    /// let named = NamedValue::new("timeout", Value::Int32(30));
80    /// assert_eq!(named.name(), "timeout");
81    /// ```
82    #[inline]
83    pub fn new(name: impl Into<String>, value: Value) -> Self {
84        Self {
85            name: name.into(),
86            value,
87        }
88    }
89
90    /// Get a reference to the name
91    ///
92    /// Returns a read-only name slice bound to this value.
93    ///
94    /// # Returns
95    ///
96    /// Returns a string slice `&str` of the name
97    ///
98    /// # Example
99    ///
100    /// ```rust
101    /// use common_rs::util::value::{NamedValue, Value};
102    ///
103    /// let named = NamedValue::new("host", Value::String("localhost".to_string()));
104    /// assert_eq!(named.name(), "host");
105    /// ```
106    #[inline]
107    pub fn name(&self) -> &str {
108        &self.name
109    }
110
111    /// Set a new name
112    ///
113    /// Updates the name bound to the current instance.
114    ///
115    /// # Parameters
116    ///
117    /// * `name` - The new name
118    ///
119    /// # Example
120    ///
121    /// ```rust
122    /// use common_rs::util::value::{NamedValue, Value};
123    ///
124    /// let mut named = NamedValue::new("old_name", Value::Bool(true));
125    /// named.set_name("new_name");
126    /// assert_eq!(named.name(), "new_name");
127    /// ```
128    #[inline]
129    pub fn set_name(&mut self, name: impl Into<String>) {
130        self.name = name.into();
131    }
132}
133
134impl Deref for NamedValue {
135    type Target = Value;
136
137    /// Dereference to the inner [`Value`]
138    ///
139    /// Allows direct invocation of methods on [`Value`], for example: `named.to::<i32>()`.
140    ///
141    /// # Returns
142    ///
143    /// Returns an immutable reference `&Value` to the inner value.
144    ///
145    /// # Example
146    ///
147    /// ```rust
148    /// use common_rs::util::value::{NamedValue, Value};
149    ///
150    /// let named = NamedValue::new("flag", Value::Bool(true));
151    /// // Call Value methods through Deref
152    /// assert_eq!(named.to::<bool>().unwrap(), true);
153    /// ```
154    #[inline]
155    fn deref(&self) -> &Self::Target {
156        &self.value
157    }
158}
159
160impl DerefMut for NamedValue {
161    /// Mutable dereference to the inner [`Value`]
162    ///
163    /// Allows in-place modification of the inner value (provided [`Value`] itself offers corresponding mutable methods).
164    ///
165    /// # Returns
166    ///
167    /// Returns a mutable reference `&mut Value` to the inner value.
168    #[inline]
169    fn deref_mut(&mut self) -> &mut Self::Target {
170        &mut self.value
171    }
172}