Skip to main content

qubit_value/
value.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Single Value Container
10//!
11//! Provides type-safe storage and access functionality for single values.
12//!
13//! # Author
14//!
15//! Haixing Hu
16
17use bigdecimal::BigDecimal;
18use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
19use num_bigint::BigInt;
20use num_traits::ToPrimitive;
21use serde::de::DeserializeOwned;
22use serde::{Deserialize, Serialize};
23use std::collections::HashMap;
24use std::time::Duration;
25use url::Url;
26
27use qubit_common::lang::argument::NumericArgument;
28use qubit_common::lang::DataType;
29
30use super::error::{ValueError, ValueResult};
31
32/// Single value container
33///
34/// Uses an enum to represent different types of values, providing
35/// type-safe value storage and access.
36///
37/// # Features
38///
39/// - Zero-cost abstraction with compile-time type checking
40/// - Supports multiple basic data types
41/// - Provides two sets of APIs for type checking and type conversion
42/// - Automatic memory management
43///
44/// # Example
45///
46/// ```rust,ignore
47/// use common_rs::util::value::Value;
48///
49/// // Create an integer value
50/// let value = Value::Int32(42);
51/// assert_eq!(value.get_int32().unwrap(), 42);
52///
53/// // Type conversion
54/// let converted = value.to::<i64>().unwrap();
55/// assert_eq!(converted, 42i64);
56///
57/// // String value
58/// let text = Value::String("hello".to_string());
59/// assert_eq!(text.get_string().unwrap(), "hello");
60/// ```
61///
62/// # Author
63///
64/// Haixing Hu
65///
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub enum Value {
68    /// Empty value (has type but no value)
69    Empty(DataType),
70    /// Boolean value
71    Bool(bool),
72    /// Character value
73    Char(char),
74    /// 8-bit signed integer
75    Int8(i8),
76    /// 16-bit signed integer
77    Int16(i16),
78    /// 32-bit signed integer
79    Int32(i32),
80    /// 64-bit signed integer
81    Int64(i64),
82    /// 128-bit signed integer
83    Int128(i128),
84    /// 8-bit unsigned integer
85    UInt8(u8),
86    /// 16-bit unsigned integer
87    UInt16(u16),
88    /// 32-bit unsigned integer
89    UInt32(u32),
90    /// 64-bit unsigned integer
91    UInt64(u64),
92    /// 128-bit unsigned integer
93    UInt128(u128),
94    /// Platform-dependent signed integer (isize)
95    IntSize(isize),
96    /// Platform-dependent unsigned integer (usize)
97    UIntSize(usize),
98    /// 32-bit floating point number
99    Float32(f32),
100    /// 64-bit floating point number
101    Float64(f64),
102    /// Big integer type
103    BigInteger(BigInt),
104    /// Big decimal type
105    BigDecimal(BigDecimal),
106    /// String
107    String(String),
108    /// Date
109    Date(NaiveDate),
110    /// Time
111    Time(NaiveTime),
112    /// Date and time
113    DateTime(NaiveDateTime),
114    /// UTC instant
115    Instant(DateTime<Utc>),
116    /// Duration type (std::time::Duration)
117    Duration(Duration),
118    /// URL type (url::Url)
119    Url(Url),
120    /// String map type (HashMap<String, String>)
121    StringMap(HashMap<String, String>),
122    /// JSON value type (serde_json::Value)
123    Json(serde_json::Value),
124}
125
126// ============================================================================
127// Getter method generation macro
128// ============================================================================
129
130/// Unified getter generation macro
131///
132/// Supports two modes:
133/// 1. `copy:` - For types implementing the Copy trait, directly returns the value
134/// 2. `ref:` - For non-Copy types, returns a reference
135///
136/// # Documentation Comment Support
137///
138/// The macro automatically extracts preceding documentation comments, so
139/// you can add `///` comments before macro invocations.
140///
141/// # Author
142///
143/// Haixing Hu
144///
145macro_rules! impl_get_value {
146    // Copy type: directly dereference and return
147    ($(#[$attr:meta])* copy: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
148        $(#[$attr])*
149        pub fn $method(&self) -> ValueResult<$type> {
150            match self {
151                Value::$variant(v) => Ok(*v),
152                Value::Empty(_) => Err(ValueError::NoValue),
153                _ => Err(ValueError::TypeMismatch {
154                    expected: $data_type,
155                    actual: self.data_type(),
156                }),
157            }
158        }
159    };
160
161    // Reference type: use conversion function to return reference,
162    // fixing lifetime issues
163    ($(#[$attr:meta])* ref: $method:ident, $variant:ident, $ret_type:ty, $data_type:expr, $conversion:expr) => {
164        $(#[$attr])*
165        pub fn $method(&self) -> ValueResult<$ret_type> {
166            match self {
167                Value::$variant(v) => {
168                    let conv_fn: fn(&_) -> $ret_type = $conversion;
169                    Ok(conv_fn(v))
170                },
171                Value::Empty(_) => Err(ValueError::NoValue),
172                _ => Err(ValueError::TypeMismatch {
173                    expected: $data_type,
174                    actual: self.data_type(),
175                }),
176            }
177        }
178    };
179}
180
181/// Unified setter generation macro
182///
183/// Supports two modes:
184/// 1. `copy:` - For types implementing the Copy trait, directly sets the value
185/// 2. `owned:` - For non-Copy types, requires owning the value
186///
187/// # Documentation Comment Support
188///
189/// The macro automatically extracts preceding documentation comments, so
190/// you can add `///` comments before macro invocations.
191///
192/// # Author
193///
194/// Haixing Hu
195///
196macro_rules! impl_set_value {
197    // Copy type: directly set the value
198    ($(#[$attr:meta])* copy: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
199        $(#[$attr])*
200        pub fn $method(&mut self, value: $type) -> ValueResult<()> {
201            *self = Value::$variant(value);
202            Ok(())
203        }
204    };
205
206    // Owned type: set the owned value
207    ($(#[$attr:meta])* owned: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
208        $(#[$attr])*
209        pub fn $method(&mut self, value: $type) -> ValueResult<()> {
210            *self = Value::$variant(value);
211            Ok(())
212        }
213    };
214}
215
216impl Value {
217    /// Generic constructor method
218    ///
219    /// Creates a `Value` from any supported type, avoiding direct use of
220    /// enum variants.
221    ///
222    /// # Supported Generic Types
223    ///
224    /// `Value::new<T>(value)` currently supports the following `T`:
225    ///
226    /// - `bool`
227    /// - `char`
228    /// - `i8`, `i16`, `i32`, `i64`, `i128`
229    /// - `u8`, `u16`, `u32`, `u64`, `u128`
230    /// - `f32`, `f64`
231    /// - `String`, `&str`
232    /// - `NaiveDate`, `NaiveTime`, `NaiveDateTime`, `DateTime<Utc>`
233    /// - `BigInt`, `BigDecimal`
234    /// - `isize`, `usize`
235    /// - `Duration`
236    /// - `Url`
237    /// - `HashMap<String, String>`
238    /// - `serde_json::Value`
239    ///
240    /// # Type Parameters
241    ///
242    /// * `T` - The type of the value to wrap
243    ///
244    /// # Returns
245    ///
246    /// Returns a `Value` wrapping the given value
247    ///
248    /// # Example
249    ///
250    /// ```rust,ignore
251    /// use crate::util::value::Value;
252    ///
253    /// // Basic types
254    /// let v = Value::new(42i32);
255    /// assert_eq!(v.get_int32().unwrap(), 42);
256    ///
257    /// let v = Value::new(true);
258    /// assert_eq!(v.get_bool().unwrap(), true);
259    ///
260    /// // String
261    /// let v = Value::new("hello".to_string());
262    /// assert_eq!(v.get_string().unwrap(), "hello");
263    /// ```
264    pub fn new<T>(value: T) -> Self
265    where
266        Self: ValueConstructor<T>,
267    {
268        <Self as ValueConstructor<T>>::from_type(value)
269    }
270
271    /// Generic getter method
272    ///
273    /// Automatically selects the correct getter method based on the target
274    /// type, performing strict type checking.
275    ///
276    /// `get<T>()` performs strict type matching. It does not do cross-type
277    /// conversion.
278    ///
279    /// For example, `Value::Int32(42).get::<i64>()` fails, while
280    /// `Value::Int32(42).to::<i64>()` succeeds.
281    ///
282    /// # Supported Generic Types
283    ///
284    /// `Value::get<T>()` currently supports the following `T`:
285    ///
286    /// - `bool`
287    /// - `char`
288    /// - `i8`, `i16`, `i32`, `i64`, `i128`
289    /// - `u8`, `u16`, `u32`, `u64`, `u128`
290    /// - `f32`, `f64`
291    /// - `String`
292    /// - `NaiveDate`, `NaiveTime`, `NaiveDateTime`, `DateTime<Utc>`
293    /// - `BigInt`, `BigDecimal`
294    /// - `isize`, `usize`
295    /// - `Duration`
296    /// - `Url`
297    /// - `HashMap<String, String>`
298    /// - `serde_json::Value`
299    ///
300    /// # Type Parameters
301    ///
302    /// * `T` - The target type to retrieve
303    ///
304    /// # Returns
305    ///
306    /// If types match, returns the value of the corresponding type;
307    /// otherwise returns an error
308    ///
309    /// # Example
310    ///
311    /// ```rust,ignore
312    /// use crate::util::value::Value;
313    ///
314    /// let value = Value::Int32(42);
315    ///
316    /// // Through type inference
317    /// let num: i32 = value.get().unwrap();
318    /// assert_eq!(num, 42);
319    ///
320    /// // Explicitly specify type parameter
321    /// let num = value.get::<i32>().unwrap();
322    /// assert_eq!(num, 42);
323    ///
324    /// // Different type
325    /// let text = Value::String("hello".to_string());
326    /// let s: String = text.get().unwrap();
327    /// assert_eq!(s, "hello");
328    ///
329    /// // Boolean value
330    /// let flag = Value::Bool(true);
331    /// let b: bool = flag.get().unwrap();
332    /// assert_eq!(b, true);
333    /// ```
334    pub fn get<T>(&self) -> ValueResult<T>
335    where
336        Self: ValueGetter<T>,
337    {
338        <Self as ValueGetter<T>>::get_value(self)
339    }
340
341    /// Generic conversion method
342    ///
343    /// Converts the current value to the target type according to the conversion
344    /// rules defined by [`ValueConverter<T>`].
345    ///
346    /// # Supported Target Types And Source Variants
347    ///
348    /// `Value::to<T>()` currently supports the following target types:
349    ///
350    /// - `bool`
351    ///   - `Value::Bool`
352    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
353    ///     `Value::Int128`
354    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
355    ///     `Value::UInt64`, `Value::UInt128`
356    ///   - `Value::String`, parsed as `bool`
357    /// - `char`
358    ///   - `Value::Char`
359    /// - `i8`
360    ///   - `Value::Int8`
361    /// - `i16`
362    ///   - `Value::Int16`
363    /// - `i32`
364    ///   - `Value::Int32`
365    ///   - `Value::Bool`
366    ///   - `Value::Char`
367    ///   - `Value::Int8`, `Value::Int16`, `Value::Int64`, `Value::Int128`
368    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
369    ///     `Value::UInt64`, `Value::UInt128`
370    ///   - `Value::Float32`, `Value::Float64`
371    ///   - `Value::String`, parsed as `i32`
372    ///   - `Value::BigInteger`, `Value::BigDecimal`
373    /// - `i64`
374    ///   - `Value::Int64`
375    ///   - `Value::Bool`
376    ///   - `Value::Char`
377    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int128`
378    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
379    ///     `Value::UInt64`, `Value::UInt128`
380    ///   - `Value::Float32`, `Value::Float64`
381    ///   - `Value::String`, parsed as `i64`
382    ///   - `Value::BigInteger`, `Value::BigDecimal`
383    /// - `i128`
384    ///   - `Value::Int128`
385    /// - `u8`
386    ///   - `Value::UInt8`
387    ///   - `Value::Bool`
388    ///   - `Value::Char`
389    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
390    ///     `Value::Int128`
391    ///   - `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
392    ///     `Value::UInt128`
393    ///   - `Value::String`, parsed as `u8`
394    /// - `u16`
395    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
396    ///     `Value::UInt64`, `Value::UInt128`
397    ///   - `Value::Bool`
398    ///   - `Value::Char`
399    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
400    ///     `Value::Int128`
401    ///   - `Value::String`, parsed as `u16`
402    /// - `u32`
403    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
404    ///     `Value::UInt64`, `Value::UInt128`
405    ///   - `Value::Bool`
406    ///   - `Value::Char`
407    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
408    ///     `Value::Int128`
409    ///   - `Value::String`, parsed as `u32`
410    /// - `u64`
411    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
412    ///     `Value::UInt64`, `Value::UInt128`
413    ///   - `Value::Bool`
414    ///   - `Value::Char`
415    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
416    ///     `Value::Int128`
417    ///   - `Value::String`, parsed as `u64`
418    /// - `u128`
419    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
420    ///     `Value::UInt64`, `Value::UInt128`
421    ///   - `Value::Bool`
422    ///   - `Value::Char`
423    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
424    ///     `Value::Int128`
425    ///   - `Value::String`, parsed as `u128`
426    /// - `f32`
427    ///   - `Value::Float32`, `Value::Float64`
428    ///   - `Value::Bool`
429    ///   - `Value::Char`
430    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
431    ///     `Value::Int128`
432    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
433    ///     `Value::UInt64`, `Value::UInt128`
434    ///   - `Value::String`, parsed as `f32`
435    ///   - `Value::BigInteger`, `Value::BigDecimal`
436    /// - `f64`
437    ///   - `Value::Float64`
438    ///   - `Value::Bool`
439    ///   - `Value::Char`
440    ///   - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
441    ///     `Value::Int128`
442    ///   - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`,
443    ///     `Value::UInt64`, `Value::UInt128`
444    ///   - `Value::Float32`
445    ///   - `Value::String`, parsed as `f64`
446    ///   - `Value::BigInteger`, `Value::BigDecimal`
447    /// - `String`
448    ///   - `Value::String`
449    ///   - `Value::Bool`, `Value::Char`
450    ///   - all integer and floating-point variants
451    ///   - `Value::Date`, `Value::Time`, `Value::DateTime`, `Value::Instant`
452    ///   - `Value::BigInteger`, `Value::BigDecimal`
453    ///   - `Value::IntSize`, `Value::UIntSize`
454    ///   - `Value::Duration`, formatted as `<nanoseconds>ns`
455    ///   - `Value::Url`
456    ///   - `Value::StringMap`, serialized as JSON text
457    ///   - `Value::Json`, serialized as JSON text
458    /// - `NaiveDate`
459    ///   - `Value::Date`
460    /// - `NaiveTime`
461    ///   - `Value::Time`
462    /// - `NaiveDateTime`
463    ///   - `Value::DateTime`
464    /// - `DateTime<Utc>`
465    ///   - `Value::Instant`
466    /// - `BigInt`
467    ///   - `Value::BigInteger`
468    /// - `BigDecimal`
469    ///   - `Value::BigDecimal`
470    /// - `isize`
471    ///   - `Value::IntSize`
472    /// - `usize`
473    ///   - `Value::UIntSize`
474    /// - `Duration`
475    ///   - `Value::Duration`
476    ///   - `Value::String`, parsed from `<nanoseconds>ns`
477    /// - `Url`
478    ///   - `Value::Url`
479    ///   - `Value::String`, parsed as URL text
480    /// - `HashMap<String, String>`
481    ///   - `Value::StringMap`
482    /// - `serde_json::Value`
483    ///   - `Value::Json`
484    ///   - `Value::String`, parsed as JSON text
485    ///   - `Value::StringMap`, converted to a JSON object
486    ///
487    /// Any target type not listed above is not supported by `Value::to<T>()`.
488    ///
489    /// # Type Parameters
490    ///
491    /// * `T` - The target type to convert to
492    ///
493    /// # Returns
494    ///
495    /// Returns the converted value on success, or an error if conversion is not
496    /// supported or fails.
497    ///
498    /// # Example
499    ///
500    /// ```rust,ignore
501    /// use crate::util::value::Value;
502    ///
503    /// let value = Value::Int32(42);
504    ///
505    /// let num: i64 = value.to().unwrap();
506    /// assert_eq!(num, 42);
507    ///
508    /// let text: String = value.to().unwrap();
509    /// assert_eq!(text, "42");
510    /// ```
511    pub fn to<T>(&self) -> ValueResult<T>
512    where
513        Self: ValueConverter<T>,
514    {
515        <Self as ValueConverter<T>>::convert(self)
516    }
517
518    /// Generic setter method
519    ///
520    /// Automatically selects the correct setter method based on the target
521    /// type, performing strict type checking.
522    ///
523    /// # Supported Generic Types
524    ///
525    /// `Value::set<T>(value)` currently supports the following `T`:
526    ///
527    /// - `bool`
528    /// - `char`
529    /// - `i8`, `i16`, `i32`, `i64`, `i128`
530    /// - `u8`, `u16`, `u32`, `u64`, `u128`
531    /// - `f32`, `f64`
532    /// - `String`, `&str`
533    /// - `NaiveDate`, `NaiveTime`, `NaiveDateTime`, `DateTime<Utc>`
534    /// - `BigInt`, `BigDecimal`
535    /// - `isize`, `usize`
536    /// - `Duration`
537    /// - `Url`
538    /// - `HashMap<String, String>`
539    /// - `serde_json::Value`
540    ///
541    /// # Type Parameters
542    ///
543    /// * `T` - The target type to set
544    ///
545    /// # Parameters
546    ///
547    /// * `value` - The value to set
548    ///
549    /// # Returns
550    ///
551    /// If setting succeeds, returns `Ok(())`; otherwise returns an error
552    ///
553    /// # Example
554    ///
555    /// ```rust,ignore
556    /// use crate::util::value::Value;
557    ///
558    /// let mut value = Value::Empty(DataType::Int32);
559    ///
560    /// // Through type inference
561    /// value.set(42i32).unwrap();
562    /// assert_eq!(value.get_int32().unwrap(), 42);
563    ///
564    /// // Explicitly specify type parameter
565    /// value.set::<i32>(100).unwrap();
566    /// assert_eq!(value.get_int32().unwrap(), 100);
567    ///
568    /// // String type
569    /// let mut text = Value::Empty(DataType::String);
570    /// text.set("hello".to_string()).unwrap();
571    /// assert_eq!(text.get_string().unwrap(), "hello");
572    /// ```
573    pub fn set<T>(&mut self, value: T) -> ValueResult<()>
574    where
575        Self: ValueSetter<T>,
576    {
577        <Self as ValueSetter<T>>::set_value(self, value)
578    }
579
580    /// Get the data type of the value
581    ///
582    /// # Returns
583    ///
584    /// Returns the data type corresponding to this value
585    ///
586    /// # Example
587    ///
588    /// ```rust,ignore
589    /// use crate::util::value::{Value, DataType};
590    ///
591    /// let value = Value::Int32(42);
592    /// assert_eq!(value.data_type(), DataType::Int32);
593    ///
594    /// let empty = Value::Empty(DataType::String);
595    /// assert_eq!(empty.data_type(), DataType::String);
596    /// ```
597    pub fn data_type(&self) -> DataType {
598        match self {
599            Value::Empty(dt) => *dt,
600            Value::Bool(_) => DataType::Bool,
601            Value::Char(_) => DataType::Char,
602            Value::Int8(_) => DataType::Int8,
603            Value::Int16(_) => DataType::Int16,
604            Value::Int32(_) => DataType::Int32,
605            Value::Int64(_) => DataType::Int64,
606            Value::Int128(_) => DataType::Int128,
607            Value::UInt8(_) => DataType::UInt8,
608            Value::UInt16(_) => DataType::UInt16,
609            Value::UInt32(_) => DataType::UInt32,
610            Value::UInt64(_) => DataType::UInt64,
611            Value::UInt128(_) => DataType::UInt128,
612            Value::Float32(_) => DataType::Float32,
613            Value::Float64(_) => DataType::Float64,
614            Value::String(_) => DataType::String,
615            Value::Date(_) => DataType::Date,
616            Value::Time(_) => DataType::Time,
617            Value::DateTime(_) => DataType::DateTime,
618            Value::Instant(_) => DataType::Instant,
619            Value::BigInteger(_) => DataType::BigInteger,
620            Value::BigDecimal(_) => DataType::BigDecimal,
621            Value::IntSize(_) => DataType::IntSize,
622            Value::UIntSize(_) => DataType::UIntSize,
623            Value::Duration(_) => DataType::Duration,
624            Value::Url(_) => DataType::Url,
625            Value::StringMap(_) => DataType::StringMap,
626            Value::Json(_) => DataType::Json,
627        }
628    }
629
630    /// Check if the value is empty
631    ///
632    /// # Returns
633    ///
634    /// Returns `true` if the value is empty
635    ///
636    /// # Example
637    ///
638    /// ```rust,ignore
639    /// use crate::util::value::{Value, DataType};
640    ///
641    /// let value = Value::Int32(42);
642    /// assert!(!value.is_empty());
643    ///
644    /// let empty = Value::Empty(DataType::String);
645    /// assert!(empty.is_empty());
646    /// ```
647    pub fn is_empty(&self) -> bool {
648        matches!(self, Value::Empty(_))
649    }
650
651    /// Clear the value while preserving the type
652    ///
653    /// Sets the current value to empty but retains its data type.
654    ///
655    /// # Example
656    ///
657    /// ```rust,ignore
658    /// use crate::util::value::{Value, DataType};
659    ///
660    /// let mut value = Value::Int32(42);
661    /// value.clear();
662    /// assert!(value.is_empty());
663    /// assert_eq!(value.data_type(), DataType::Int32);
664    /// ```
665    pub fn clear(&mut self) {
666        let dt = self.data_type();
667        *self = Value::Empty(dt);
668    }
669
670    /// Set the data type
671    ///
672    /// If the new type differs from the current type, clears the value
673    /// and sets the new type.
674    ///
675    /// # Parameters
676    ///
677    /// * `data_type` - The data type to set
678    ///
679    /// # Example
680    ///
681    /// ```rust,ignore
682    /// use crate::util::value::{Value, DataType};
683    ///
684    /// let mut value = Value::Int32(42);
685    /// value.set_type(DataType::String);
686    /// assert!(value.is_empty());
687    /// assert_eq!(value.data_type(), DataType::String);
688    /// ```
689    pub fn set_type(&mut self, data_type: DataType) {
690        if self.data_type() != data_type {
691            *self = Value::Empty(data_type);
692        }
693    }
694
695    // ========================================================================
696    // Type-checking getters (strict type matching)
697    // ========================================================================
698
699    impl_get_value! {
700        /// Get boolean value
701        ///
702        /// # Returns
703        ///
704        /// If types match, returns the boolean value; otherwise returns an
705        /// error.
706        ///
707        /// # Example
708        ///
709        /// ```rust,ignore
710        /// use crate::util::value::Value;
711        ///
712        /// let value = Value::Bool(true);
713        /// assert_eq!(value.get_bool().unwrap(), true);
714        /// ```
715        copy: get_bool, Bool, bool, DataType::Bool
716    }
717
718    impl_get_value! {
719        /// Get character value
720        ///
721        /// # Returns
722        ///
723        /// If types match, returns the character value; otherwise returns an
724        /// error.
725        ///
726        /// # Example
727        ///
728        /// ```rust,ignore
729        /// use crate::util::value::Value;
730        ///
731        /// let value = Value::Char('A');
732        /// assert_eq!(value.get_char().unwrap(), 'A');
733        /// ```
734        copy: get_char, Char, char, DataType::Char
735    }
736
737    impl_get_value! {
738        /// Get int8 value
739        ///
740        /// # Returns
741        ///
742        /// If types match, returns the int8 value; otherwise returns an error.
743        copy: get_int8, Int8, i8, DataType::Int8
744    }
745
746    impl_get_value! {
747        /// Get int16 value
748        ///
749        /// # Returns
750        ///
751        /// If types match, returns the int16 value; otherwise returns an error
752        copy: get_int16, Int16, i16, DataType::Int16
753    }
754
755    impl_get_value! {
756        /// Get int32 value
757        ///
758        /// # Returns
759        ///
760        /// If types match, returns the int32 value; otherwise returns an error.
761        copy: get_int32, Int32, i32, DataType::Int32
762    }
763
764    impl_get_value! {
765        /// Get int64 value
766        ///
767        /// # Returns
768        ///
769        /// If types match, returns the int64 value; otherwise returns an error
770        copy: get_int64, Int64, i64, DataType::Int64
771    }
772
773    impl_get_value! {
774        /// Get int128 value
775        ///
776        /// # Returns
777        ///
778        /// If types match, returns the int128 value; otherwise returns an error.
779        copy: get_int128, Int128, i128, DataType::Int128
780    }
781
782    impl_get_value! {
783        /// Get uint8 value
784        ///
785        /// # Returns
786        ///
787        /// If types match, returns the uint8 value; otherwise returns an error
788        copy: get_uint8, UInt8, u8, DataType::UInt8
789    }
790
791    impl_get_value! {
792        /// Get uint16 value
793        ///
794        /// # Returns
795        ///
796        /// If types match, returns the uint16 value; otherwise returns an error.
797        copy: get_uint16, UInt16, u16, DataType::UInt16
798    }
799
800    impl_get_value! {
801        /// Get uint32 value
802        ///
803        /// # Returns
804        ///
805        /// If types match, returns the uint32 value; otherwise returns an error.
806        copy: get_uint32, UInt32, u32, DataType::UInt32
807    }
808
809    impl_get_value! {
810        /// Get uint64 value
811        ///
812        /// # Returns
813        ///
814        /// If types match, returns the uint64 value; otherwise returns an error.
815        copy: get_uint64, UInt64, u64, DataType::UInt64
816    }
817
818    impl_get_value! {
819        /// Get uint128 value
820        ///
821        /// # Returns
822        ///
823        /// If types match, returns the uint128 value; otherwise returns an error
824        copy: get_uint128, UInt128, u128, DataType::UInt128
825    }
826
827    impl_get_value! {
828        /// Get float32 value
829        ///
830        /// # Returns
831        ///
832        /// If types match, returns the float32 value; otherwise returns an error.
833        copy: get_float32, Float32, f32, DataType::Float32
834    }
835
836    impl_get_value! {
837        /// Get float64 value
838        ///
839        /// # Returns
840        ///
841        /// If types match, returns the float64 value; otherwise returns an error
842        copy: get_float64, Float64, f64, DataType::Float64
843    }
844
845    impl_get_value! {
846        /// Get string reference
847        ///
848        /// # Returns
849        ///
850        /// If types match, returns a reference to the string; otherwise returns
851        /// an error.
852        ///
853        /// # Example
854        ///
855        /// ```rust,ignore
856        /// use crate::util::value::Value;
857        ///
858        /// let value = Value::String("hello".to_string());
859        /// assert_eq!(value.get_string().unwrap(), "hello");
860        /// ```
861        ref: get_string, String, &str, DataType::String, |s: &String| s.as_str()
862    }
863
864    impl_get_value! {
865        /// Get date value
866        ///
867        /// # Returns
868        ///
869        /// If types match, returns the date value; otherwise returns an error.
870        copy: get_date, Date, NaiveDate, DataType::Date
871    }
872
873    impl_get_value! {
874        /// Get time value
875        ///
876        /// # Returns
877        ///
878        /// If types match, returns the time value; otherwise returns an error.
879        copy: get_time, Time, NaiveTime, DataType::Time
880    }
881
882    impl_get_value! {
883        /// Get datetime value
884        ///
885        /// # Returns
886        ///
887        /// If types match, returns the datetime value; otherwise returns an error.
888        copy: get_datetime, DateTime, NaiveDateTime, DataType::DateTime
889    }
890
891    impl_get_value! {
892        /// Get UTC instant value
893        ///
894        /// # Returns
895        ///
896        /// If types match, returns the UTC instant value; otherwise returns an error.
897        copy: get_instant, Instant, DateTime<Utc>, DataType::Instant
898    }
899
900    impl_get_value! {
901        /// Get big integer value
902        ///
903        /// # Returns
904        ///
905        /// If types match, returns the big integer value; otherwise returns an error.
906        ///
907        /// # Example
908        ///
909        /// ```rust,ignore
910        /// use crate::util::value::Value;
911        /// use num_bigint::BigInt;
912        ///
913        /// let value = Value::BigInteger(BigInt::from(123456789));
914        /// assert_eq!(value.get_biginteger().unwrap(), BigInt::from(123456789));
915        /// ```
916        ref: get_biginteger, BigInteger, BigInt, DataType::BigInteger, |v: &BigInt| v.clone()
917    }
918
919    impl_get_value! {
920        /// Get big decimal value
921        ///
922        /// # Returns
923        ///
924        /// If types match, returns the big decimal value; otherwise returns an
925        /// error.
926        ///
927        /// # Example
928        ///
929        /// ```rust,ignore
930        /// use crate::util::value::Value;
931        /// use bigdecimal::BigDecimal;
932        ///
933        /// let value = Value::BigDecimal(BigDecimal::from(123.456));
934        /// assert_eq!(value.get_bigdecimal().unwrap(), BigDecimal::from(123.456));
935        /// ```
936        ref: get_bigdecimal, BigDecimal, BigDecimal, DataType::BigDecimal, |v: &BigDecimal| v.clone()
937    }
938
939    // ========================================================================
940    // Type-setting setters (strict type matching)
941    // ========================================================================
942
943    impl_set_value! {
944        /// Set boolean value
945        ///
946        /// # Parameters
947        ///
948        /// * `value` - The boolean value to set
949        ///
950        /// # Returns
951        ///
952        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
953        ///
954        /// # Example
955        ///
956        /// ```rust,ignore
957        /// use crate::util::value::Value;
958        ///
959        /// let mut value = Value::Empty(DataType::Bool);
960        /// value.set_bool(true).unwrap();
961        /// assert_eq!(value.get_bool().unwrap(), true);
962        /// ```
963        copy: set_bool, Bool, bool, DataType::Bool
964    }
965
966    impl_set_value! {
967        /// Set character value
968        ///
969        /// # Parameters
970        ///
971        /// * `value` - The character value to set
972        ///
973        /// # Returns
974        ///
975        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
976        copy: set_char, Char, char, DataType::Char
977    }
978
979    impl_set_value! {
980        /// Set int8 value
981        ///
982        /// # Parameters
983        ///
984        /// * `value` - The int8 value to set
985        ///
986        /// # Returns
987        ///
988        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
989        copy: set_int8, Int8, i8, DataType::Int8
990    }
991
992    impl_set_value! {
993        /// Set int16 value
994        ///
995        /// # Parameters
996        ///
997        /// * `value` - The int16 value to set
998        ///
999        /// # Returns
1000        ///
1001        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1002        copy: set_int16, Int16, i16, DataType::Int16
1003    }
1004
1005    impl_set_value! {
1006        /// Set int32 value
1007        ///
1008        /// # Parameters
1009        ///
1010        /// * `value` - The int32 value to set
1011        ///
1012        /// # Returns
1013        ///
1014        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1015        copy: set_int32, Int32, i32, DataType::Int32
1016    }
1017
1018    impl_set_value! {
1019        /// Set int64 value
1020        ///
1021        /// # Parameters
1022        ///
1023        /// * `value` - The int64 value to set
1024        ///
1025        /// # Returns
1026        ///
1027        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1028        copy: set_int64, Int64, i64, DataType::Int64
1029    }
1030
1031    impl_set_value! {
1032        /// Set int128 value
1033        ///
1034        /// # Parameters
1035        ///
1036        /// * `value` - The int128 value to set
1037        ///
1038        /// # Returns
1039        ///
1040        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1041        copy: set_int128, Int128, i128, DataType::Int128
1042    }
1043
1044    impl_set_value! {
1045        /// Set uint8 value
1046        ///
1047        /// # Parameters
1048        ///
1049        /// * `value` - The uint8 value to set
1050        ///
1051        /// # Returns
1052        ///
1053        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1054        copy: set_uint8, UInt8, u8, DataType::UInt8
1055    }
1056
1057    impl_set_value! {
1058        /// Set uint16 value
1059        ///
1060        /// # Parameters
1061        ///
1062        /// * `value` - The uint16 value to set
1063        ///
1064        /// # Returns
1065        ///
1066        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1067        copy: set_uint16, UInt16, u16, DataType::UInt16
1068    }
1069
1070    impl_set_value! {
1071        /// Set uint32 value
1072        ///
1073        /// # Parameters
1074        ///
1075        /// * `value` - The uint32 value to set
1076        ///
1077        /// # Returns
1078        ///
1079        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1080        copy: set_uint32, UInt32, u32, DataType::UInt32
1081    }
1082
1083    impl_set_value! {
1084        /// Set uint64 value
1085        ///
1086        /// # Parameters
1087        ///
1088        /// * `value` - The uint64 value to set
1089        ///
1090        /// # Returns
1091        ///
1092        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1093        copy: set_uint64, UInt64, u64, DataType::UInt64
1094    }
1095
1096    impl_set_value! {
1097        /// Set uint128 value
1098        ///
1099        /// # Parameters
1100        ///
1101        /// * `value` - The uint128 value to set
1102        ///
1103        /// # Returns
1104        ///
1105        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1106        copy: set_uint128, UInt128, u128, DataType::UInt128
1107    }
1108
1109    impl_set_value! {
1110        /// Set float32 value
1111        ///
1112        /// # Parameters
1113        ///
1114        /// * `value` - The float32 value to set
1115        ///
1116        /// # Returns
1117        ///
1118        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1119        copy: set_float32, Float32, f32, DataType::Float32
1120    }
1121
1122    impl_set_value! {
1123        /// Set float64 value
1124        ///
1125        /// # Parameters
1126        ///
1127        /// * `value` - The float64 value to set
1128        ///
1129        /// # Returns
1130        ///
1131        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1132        copy: set_float64, Float64, f64, DataType::Float64
1133    }
1134
1135    impl_set_value! {
1136        /// Set string value
1137        ///
1138        /// # Parameters
1139        ///
1140        /// * `value` - The string value to set
1141        ///
1142        /// # Returns
1143        ///
1144        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1145        ///
1146        /// # Example
1147        ///
1148        /// ```rust,ignore
1149        /// use crate::util::value::Value;
1150        ///
1151        /// let mut value = Value::Empty(DataType::String);
1152        /// value.set_string("hello".to_string()).unwrap();
1153        /// assert_eq!(value.get_string().unwrap(), "hello");
1154        /// ```
1155        owned: set_string, String, String, DataType::String
1156    }
1157
1158    impl_set_value! {
1159        /// Set date value
1160        ///
1161        /// # Parameters
1162        ///
1163        /// * `value` - The date value to set
1164        ///
1165        /// # Returns
1166        ///
1167        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1168        copy: set_date, Date, NaiveDate, DataType::Date
1169    }
1170
1171    impl_set_value! {
1172        /// Set time value
1173        ///
1174        /// # Parameters
1175        ///
1176        /// * `value` - The time value to set
1177        ///
1178        /// # Returns
1179        ///
1180        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1181        copy: set_time, Time, NaiveTime, DataType::Time
1182    }
1183
1184    impl_set_value! {
1185        /// Set datetime value
1186        ///
1187        /// # Parameters
1188        ///
1189        /// * `value` - The datetime value to set
1190        ///
1191        /// # Returns
1192        ///
1193        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1194        copy: set_datetime, DateTime, NaiveDateTime, DataType::DateTime
1195    }
1196
1197    impl_set_value! {
1198        /// Set UTC instant value
1199        ///
1200        /// # Parameters
1201        ///
1202        /// * `value` - The UTC instant value to set
1203        ///
1204        /// # Returns
1205        ///
1206        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1207        copy: set_instant, Instant, DateTime<Utc>, DataType::Instant
1208    }
1209
1210    impl_set_value! {
1211        /// Set big integer value
1212        ///
1213        /// # Parameters
1214        ///
1215        /// * `value` - The big integer value to set
1216        ///
1217        /// # Returns
1218        ///
1219        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1220        ///
1221        /// # Example
1222        ///
1223        /// ```rust,ignore
1224        /// use crate::util::value::Value;
1225        /// use num_bigint::BigInt;
1226        ///
1227        /// let mut value = Value::Empty(DataType::BigInteger);
1228        /// value.set_biginteger(BigInt::from(123456789)).unwrap();
1229        /// assert_eq!(value.get_biginteger().unwrap(), BigInt::from(123456789));
1230        /// ```
1231        owned: set_biginteger, BigInteger, BigInt, DataType::BigInteger
1232    }
1233
1234    impl_set_value! {
1235        /// Set big decimal value
1236        ///
1237        /// # Parameters
1238        ///
1239        /// * `value` - The big decimal value to set
1240        ///
1241        /// # Returns
1242        ///
1243        /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
1244        ///
1245        /// # Example
1246        ///
1247        /// ```rust,ignore
1248        /// use crate::util::value::Value;
1249        /// use bigdecimal::BigDecimal;
1250        ///
1251        /// let mut value = Value::Empty(DataType::BigDecimal);
1252        /// value.set_bigdecimal(BigDecimal::from(123.456)).unwrap();
1253        /// assert_eq!(value.get_bigdecimal().unwrap(), BigDecimal::from(123.456));
1254        /// ```
1255        owned: set_bigdecimal, BigDecimal, BigDecimal, DataType::BigDecimal
1256    }
1257
1258    impl_get_value! {
1259        /// Get isize value
1260        ///
1261        /// # Returns
1262        ///
1263        /// If types match, returns the isize value; otherwise returns an error.
1264        copy: get_intsize, IntSize, isize, DataType::IntSize
1265    }
1266
1267    impl_get_value! {
1268        /// Get usize value
1269        ///
1270        /// # Returns
1271        ///
1272        /// If types match, returns the usize value; otherwise returns an error.
1273        copy: get_uintsize, UIntSize, usize, DataType::UIntSize
1274    }
1275
1276    impl_get_value! {
1277        /// Get Duration value
1278        ///
1279        /// # Returns
1280        ///
1281        /// If types match, returns the Duration value; otherwise returns an
1282        /// error.
1283        copy: get_duration, Duration, Duration, DataType::Duration
1284    }
1285
1286    impl_get_value! {
1287        /// Get Url reference
1288        ///
1289        /// # Returns
1290        ///
1291        /// If types match, returns a reference to the Url; otherwise returns an
1292        /// error.
1293        ref: get_url, Url, Url, DataType::Url, |v: &Url| v.clone()
1294    }
1295
1296    impl_get_value! {
1297        /// Get StringMap reference
1298        ///
1299        /// # Returns
1300        ///
1301        /// If types match, returns a reference to the `HashMap<String, String>`;
1302        /// otherwise returns an error.
1303        ref: get_string_map, StringMap, HashMap<String, String>, DataType::StringMap,
1304            |v: &HashMap<String, String>| v.clone()
1305    }
1306
1307    impl_get_value! {
1308        /// Get Json value reference
1309        ///
1310        /// # Returns
1311        ///
1312        /// If types match, returns a reference to the `serde_json::Value`;
1313        /// otherwise returns an error.
1314        ref: get_json, Json, serde_json::Value, DataType::Json,
1315            |v: &serde_json::Value| v.clone()
1316    }
1317
1318    impl_set_value! {
1319        /// Set isize value
1320        copy: set_intsize, IntSize, isize, DataType::IntSize
1321    }
1322
1323    impl_set_value! {
1324        /// Set usize value
1325        copy: set_uintsize, UIntSize, usize, DataType::UIntSize
1326    }
1327
1328    impl_set_value! {
1329        /// Set Duration value
1330        copy: set_duration, Duration, Duration, DataType::Duration
1331    }
1332
1333    impl_set_value! {
1334        /// Set Url value
1335        owned: set_url, Url, Url, DataType::Url
1336    }
1337
1338    impl_set_value! {
1339        /// Set StringMap value
1340        owned: set_string_map, StringMap, HashMap<String, String>, DataType::StringMap
1341    }
1342
1343    impl_set_value! {
1344        /// Set Json value
1345        owned: set_json, Json, serde_json::Value, DataType::Json
1346    }
1347
1348    /// Create a `Value` from a `serde_json::Value`.
1349    ///
1350    /// # Parameters
1351    ///
1352    /// * `json` - The JSON value to wrap.
1353    ///
1354    /// # Returns
1355    ///
1356    /// Returns a `Value::Json` wrapping the given JSON value.
1357    pub fn from_json_value(json: serde_json::Value) -> Self {
1358        Value::Json(json)
1359    }
1360
1361    /// Create a `Value` from any serializable value by converting it to JSON.
1362    ///
1363    /// # Type Parameters
1364    ///
1365    /// * `T` - Any type implementing `Serialize`.
1366    ///
1367    /// # Parameters
1368    ///
1369    /// * `value` - The value to serialize into JSON.
1370    ///
1371    /// # Returns
1372    ///
1373    /// Returns `Ok(Value::Json(...))` on success, or an error if
1374    /// serialization fails.
1375    pub fn from_serializable<T: Serialize>(value: &T) -> ValueResult<Self> {
1376        let json = serde_json::to_value(value)
1377            .map_err(|e| ValueError::JsonSerializationError(e.to_string()))?;
1378        Ok(Value::Json(json))
1379    }
1380
1381    /// Deserialize the inner JSON value into a target type.
1382    ///
1383    /// Only works when `self` is `Value::Json(...)`.
1384    ///
1385    /// # Type Parameters
1386    ///
1387    /// * `T` - The target type implementing `DeserializeOwned`.
1388    ///
1389    /// # Returns
1390    ///
1391    /// Returns `Ok(T)` on success, or an error if the value is not JSON
1392    /// or deserialization fails.
1393    pub fn deserialize_json<T: DeserializeOwned>(&self) -> ValueResult<T> {
1394        match self {
1395            Value::Json(v) => serde_json::from_value(v.clone())
1396                .map_err(|e| ValueError::JsonDeserializationError(e.to_string())),
1397            Value::Empty(_) => Err(ValueError::NoValue),
1398            _ => Err(ValueError::ConversionFailed {
1399                from: self.data_type(),
1400                to: DataType::Json,
1401            }),
1402        }
1403    }
1404}
1405
1406impl Default for Value {
1407    fn default() -> Self {
1408        Value::Empty(DataType::String)
1409    }
1410}
1411
1412fn parse_duration_string(s: &str) -> ValueResult<Duration> {
1413    let trimmed = s.trim();
1414    let nanos_text = trimmed.strip_suffix("ns").ok_or_else(|| {
1415        ValueError::ConversionError(format!(
1416            "Cannot convert '{}' to Duration: expected '<nanoseconds>ns'",
1417            s
1418        ))
1419    })?;
1420    let total_nanos = nanos_text.parse::<u128>().map_err(|_| {
1421        ValueError::ConversionError(format!(
1422            "Cannot convert '{}' to Duration: invalid nanoseconds value",
1423            s
1424        ))
1425    })?;
1426    let secs = total_nanos / 1_000_000_000;
1427    if secs > u64::MAX as u128 {
1428        return Err(ValueError::ConversionError(format!(
1429            "Cannot convert '{}' to Duration: value out of range",
1430            s
1431        )));
1432    }
1433    let nanos = (total_nanos % 1_000_000_000) as u32;
1434    Ok(Duration::new(secs as u64, nanos))
1435}
1436
1437fn range_check<T>(value: T, min: T, max: T, target: &str) -> ValueResult<T>
1438where
1439    T: NumericArgument + Copy,
1440{
1441    value
1442        .require_in_closed_range("value", min, max)
1443        .map_err(|e| {
1444            ValueError::ConversionError(format!("Cannot convert value to {}: {}", target, e))
1445        })
1446}
1447
1448// ============================================================================
1449// Internal generic conversion traits (private, not exported, to avoid
1450// polluting the standard type namespace)
1451// ============================================================================
1452
1453/// Internal trait: used to extract specific types from Value.
1454///
1455/// This trait is not exported in mod.rs, only used for internal
1456/// implementation, to avoid polluting the standard type namespace.
1457#[doc(hidden)]
1458pub trait ValueGetter<T> {
1459    fn get_value(&self) -> ValueResult<T>;
1460}
1461
1462/// Internal trait: used to create Value from types.
1463///
1464/// This trait is not exported in mod.rs, only used for internal
1465/// implementation, to avoid polluting the standard type namespace.
1466#[doc(hidden)]
1467pub trait ValueConstructor<T> {
1468    fn from_type(value: T) -> Self;
1469}
1470
1471/// Internal trait: used to set specific types in Value.
1472///
1473/// This trait is not exported in mod.rs, only used for internal
1474/// implementation, to avoid polluting the standard type namespace.
1475#[doc(hidden)]
1476pub trait ValueSetter<T> {
1477    fn set_value(&mut self, value: T) -> ValueResult<()>;
1478}
1479
1480/// Internal trait: used to convert Value to target types
1481///
1482/// This trait powers `Value::to<T>()`. Each implementation must clearly define
1483/// which source variants are accepted for the target type.
1484#[doc(hidden)]
1485pub trait ValueConverter<T> {
1486    fn convert(&self) -> ValueResult<T>;
1487}
1488
1489// ============================================================================
1490// Implementation of internal traits (simplified using macros)
1491// ============================================================================
1492
1493macro_rules! impl_value_traits {
1494    ($type:ty, $variant:ident, $get_method:ident, $set_method:ident) => {
1495        impl ValueGetter<$type> for Value {
1496            fn get_value(&self) -> ValueResult<$type> {
1497                self.$get_method()
1498            }
1499        }
1500
1501        impl ValueSetter<$type> for Value {
1502            fn set_value(&mut self, value: $type) -> ValueResult<()> {
1503                self.$set_method(value)
1504            }
1505        }
1506
1507        impl ValueConstructor<$type> for Value {
1508            fn from_type(value: $type) -> Self {
1509                Value::$variant(value)
1510            }
1511        }
1512    };
1513}
1514
1515macro_rules! impl_strict_value_converter {
1516    ($(#[$attr:meta])* $type:ty, $get_method:ident) => {
1517        $(#[$attr])*
1518        impl ValueConverter<$type> for Value {
1519            fn convert(&self) -> ValueResult<$type> {
1520                self.$get_method()
1521            }
1522        }
1523    };
1524}
1525
1526// Implementation for Copy types
1527impl_value_traits!(bool, Bool, get_bool, set_bool);
1528impl_value_traits!(char, Char, get_char, set_char);
1529impl_value_traits!(i8, Int8, get_int8, set_int8);
1530impl_value_traits!(i16, Int16, get_int16, set_int16);
1531impl_value_traits!(i32, Int32, get_int32, set_int32);
1532impl_value_traits!(i64, Int64, get_int64, set_int64);
1533impl_value_traits!(i128, Int128, get_int128, set_int128);
1534impl_value_traits!(u8, UInt8, get_uint8, set_uint8);
1535impl_value_traits!(u16, UInt16, get_uint16, set_uint16);
1536impl_value_traits!(u32, UInt32, get_uint32, set_uint32);
1537impl_value_traits!(u64, UInt64, get_uint64, set_uint64);
1538impl_value_traits!(u128, UInt128, get_uint128, set_uint128);
1539impl_value_traits!(f32, Float32, get_float32, set_float32);
1540impl_value_traits!(f64, Float64, get_float64, set_float64);
1541impl_value_traits!(NaiveDate, Date, get_date, set_date);
1542impl_value_traits!(NaiveTime, Time, get_time, set_time);
1543impl_value_traits!(NaiveDateTime, DateTime, get_datetime, set_datetime);
1544impl_value_traits!(DateTime<Utc>, Instant, get_instant, set_instant);
1545impl_value_traits!(BigInt, BigInteger, get_biginteger, set_biginteger);
1546impl_value_traits!(BigDecimal, BigDecimal, get_bigdecimal, set_bigdecimal);
1547impl_value_traits!(isize, IntSize, get_intsize, set_intsize);
1548impl_value_traits!(usize, UIntSize, get_uintsize, set_uintsize);
1549impl_value_traits!(Duration, Duration, get_duration, set_duration);
1550
1551// String needs cloning
1552impl ValueGetter<String> for Value {
1553    fn get_value(&self) -> ValueResult<String> {
1554        self.get_string().map(|s| s.to_string())
1555    }
1556}
1557
1558impl ValueSetter<String> for Value {
1559    fn set_value(&mut self, value: String) -> ValueResult<()> {
1560        self.set_string(value)
1561    }
1562}
1563
1564impl ValueConstructor<String> for Value {
1565    fn from_type(value: String) -> Self {
1566        Value::String(value)
1567    }
1568}
1569
1570/// Target type `String` supports conversion from:
1571///
1572/// - `Value::String`
1573/// - `Value::Bool`, `Value::Char`
1574/// - all integer and floating-point variants
1575/// - `Value::Date`, `Value::Time`, `Value::DateTime`, `Value::Instant`
1576/// - `Value::BigInteger`, `Value::BigDecimal`
1577/// - `Value::IntSize`, `Value::UIntSize`
1578/// - `Value::Duration`, formatted as `<nanoseconds>ns`
1579/// - `Value::Url`
1580/// - `Value::StringMap`, serialized as JSON text
1581/// - `Value::Json`, serialized as JSON text
1582impl ValueConverter<String> for Value {
1583    fn convert(&self) -> ValueResult<String> {
1584        match self {
1585            Value::String(v) => Ok(v.clone()),
1586            Value::Bool(v) => Ok(v.to_string()),
1587            Value::Char(v) => Ok(v.to_string()),
1588            Value::Int8(v) => Ok(v.to_string()),
1589            Value::Int16(v) => Ok(v.to_string()),
1590            Value::Int32(v) => Ok(v.to_string()),
1591            Value::Int64(v) => Ok(v.to_string()),
1592            Value::Int128(v) => Ok(v.to_string()),
1593            Value::UInt8(v) => Ok(v.to_string()),
1594            Value::UInt16(v) => Ok(v.to_string()),
1595            Value::UInt32(v) => Ok(v.to_string()),
1596            Value::UInt64(v) => Ok(v.to_string()),
1597            Value::UInt128(v) => Ok(v.to_string()),
1598            Value::Float32(v) => Ok(v.to_string()),
1599            Value::Float64(v) => Ok(v.to_string()),
1600            Value::Date(v) => Ok(v.to_string()),
1601            Value::Time(v) => Ok(v.to_string()),
1602            Value::DateTime(v) => Ok(v.to_string()),
1603            Value::Instant(v) => Ok(v.to_rfc3339()),
1604            Value::BigInteger(v) => Ok(v.to_string()),
1605            Value::BigDecimal(v) => Ok(v.to_string()),
1606            Value::IntSize(v) => Ok(v.to_string()),
1607            Value::UIntSize(v) => Ok(v.to_string()),
1608            Value::Duration(v) => Ok(format!("{}ns", v.as_nanos())),
1609            Value::Url(v) => Ok(v.to_string()),
1610            Value::StringMap(v) => serde_json::to_string(v)
1611                .map_err(|e| ValueError::JsonSerializationError(e.to_string())),
1612            Value::Json(v) => serde_json::to_string(v)
1613                .map_err(|e| ValueError::JsonSerializationError(e.to_string())),
1614            Value::Empty(_) => Err(ValueError::NoValue),
1615        }
1616    }
1617}
1618
1619// Special handling for &str - convert to String
1620impl ValueSetter<&str> for Value {
1621    fn set_value(&mut self, value: &str) -> ValueResult<()> {
1622        self.set_string(value.to_string())
1623    }
1624}
1625
1626impl ValueConstructor<&str> for Value {
1627    fn from_type(value: &str) -> Self {
1628        Value::String(value.to_string())
1629    }
1630}
1631
1632/// Target type `bool` supports conversion from:
1633///
1634/// - `Value::Bool`
1635/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
1636///   `Value::Int128`
1637/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
1638///   `Value::UInt128`
1639/// - `Value::String`, parsed as `bool`
1640impl ValueConverter<bool> for Value {
1641    fn convert(&self) -> ValueResult<bool> {
1642        match self {
1643            Value::Bool(v) => Ok(*v),
1644            Value::Int8(v) => Ok(*v != 0),
1645            Value::Int16(v) => Ok(*v != 0),
1646            Value::Int32(v) => Ok(*v != 0),
1647            Value::Int64(v) => Ok(*v != 0),
1648            Value::Int128(v) => Ok(*v != 0),
1649            Value::UInt8(v) => Ok(*v != 0),
1650            Value::UInt16(v) => Ok(*v != 0),
1651            Value::UInt32(v) => Ok(*v != 0),
1652            Value::UInt64(v) => Ok(*v != 0),
1653            Value::UInt128(v) => Ok(*v != 0),
1654            Value::String(s) => s.parse::<bool>().map_err(|_| {
1655                ValueError::ConversionError(format!("Cannot convert '{}' to boolean", s))
1656            }),
1657            Value::Empty(_) => Err(ValueError::NoValue),
1658            _ => Err(ValueError::ConversionFailed {
1659                from: self.data_type(),
1660                to: DataType::Bool,
1661            }),
1662        }
1663    }
1664}
1665
1666/// Target type `i32` supports conversion from:
1667///
1668/// - `Value::Int32`
1669/// - `Value::Bool`
1670/// - `Value::Char`
1671/// - `Value::Int8`, `Value::Int16`, `Value::Int64`, `Value::Int128`
1672/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
1673///   `Value::UInt128`
1674/// - `Value::Float32`, `Value::Float64`
1675/// - `Value::String`, parsed as `i32`
1676/// - `Value::BigInteger`, `Value::BigDecimal`
1677impl ValueConverter<i32> for Value {
1678    fn convert(&self) -> ValueResult<i32> {
1679        match self {
1680            Value::Int32(v) => Ok(*v),
1681            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
1682            Value::Char(v) => Ok(*v as i32),
1683            Value::Int8(v) => Ok(*v as i32),
1684            Value::Int16(v) => Ok(*v as i32),
1685            Value::Int64(v) => (*v)
1686                .try_into()
1687                .map_err(|_| ValueError::ConversionError("i64 value out of i32 range".to_string())),
1688            Value::Int128(v) => (*v).try_into().map_err(|_| {
1689                ValueError::ConversionError("i128 value out of i32 range".to_string())
1690            }),
1691            Value::UInt8(v) => Ok(*v as i32),
1692            Value::UInt16(v) => Ok(*v as i32),
1693            Value::UInt32(v) => (*v)
1694                .try_into()
1695                .map_err(|_| ValueError::ConversionError("u32 value out of i32 range".to_string())),
1696            Value::UInt64(v) => (*v)
1697                .try_into()
1698                .map_err(|_| ValueError::ConversionError("u64 value out of i32 range".to_string())),
1699            Value::UInt128(v) => (*v).try_into().map_err(|_| {
1700                ValueError::ConversionError("u128 value out of i32 range".to_string())
1701            }),
1702            Value::Float32(v) => Ok(*v as i32),
1703            Value::Float64(v) => Ok(*v as i32),
1704            Value::String(s) => s
1705                .parse::<i32>()
1706                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to i32", s))),
1707            Value::Empty(_) => Err(ValueError::NoValue),
1708            Value::BigInteger(v) => v.to_i32().ok_or_else(|| {
1709                ValueError::ConversionError("BigInteger value out of i32 range".to_string())
1710            }),
1711            Value::BigDecimal(v) => v.to_i32().ok_or_else(|| {
1712                ValueError::ConversionError(
1713                    "BigDecimal value cannot be converted to i32".to_string(),
1714                )
1715            }),
1716            _ => Err(ValueError::ConversionFailed {
1717                from: self.data_type(),
1718                to: DataType::Int32,
1719            }),
1720        }
1721    }
1722}
1723
1724/// Target type `i64` supports conversion from:
1725///
1726/// - `Value::Int64`
1727/// - `Value::Bool`
1728/// - `Value::Char`
1729/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int128`
1730/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
1731///   `Value::UInt128`
1732/// - `Value::Float32`, `Value::Float64`
1733/// - `Value::String`, parsed as `i64`
1734/// - `Value::BigInteger`, `Value::BigDecimal`
1735impl ValueConverter<i64> for Value {
1736    fn convert(&self) -> ValueResult<i64> {
1737        match self {
1738            Value::Int64(v) => Ok(*v),
1739            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
1740            Value::Char(v) => Ok(*v as i64),
1741            Value::Int8(v) => Ok(*v as i64),
1742            Value::Int16(v) => Ok(*v as i64),
1743            Value::Int32(v) => Ok(*v as i64),
1744            Value::Int128(v) => (*v).try_into().map_err(|_| {
1745                ValueError::ConversionError("i128 value out of i64 range".to_string())
1746            }),
1747            Value::UInt8(v) => Ok(*v as i64),
1748            Value::UInt16(v) => Ok(*v as i64),
1749            Value::UInt32(v) => Ok(*v as i64),
1750            Value::UInt64(v) => (*v)
1751                .try_into()
1752                .map_err(|_| ValueError::ConversionError("u64 value out of i64 range".to_string())),
1753            Value::UInt128(v) => (*v).try_into().map_err(|_| {
1754                ValueError::ConversionError("u128 value out of i64 range".to_string())
1755            }),
1756            Value::Float32(v) => Ok(*v as i64),
1757            Value::Float64(v) => Ok(*v as i64),
1758            Value::String(s) => s
1759                .parse::<i64>()
1760                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to i64", s))),
1761            Value::Empty(_) => Err(ValueError::NoValue),
1762            Value::BigInteger(v) => v.to_i64().ok_or_else(|| {
1763                ValueError::ConversionError("BigInteger value out of i64 range".to_string())
1764            }),
1765            Value::BigDecimal(v) => v.to_i64().ok_or_else(|| {
1766                ValueError::ConversionError(
1767                    "BigDecimal value cannot be converted to i64".to_string(),
1768                )
1769            }),
1770            _ => Err(ValueError::ConversionFailed {
1771                from: self.data_type(),
1772                to: DataType::Int64,
1773            }),
1774        }
1775    }
1776}
1777
1778/// Target type `f64` supports conversion from:
1779///
1780/// - `Value::Float64`
1781/// - `Value::Bool`
1782/// - `Value::Char`
1783/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
1784///   `Value::Int128`
1785/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
1786///   `Value::UInt128`
1787/// - `Value::Float32`
1788/// - `Value::String`, parsed as `f64`
1789/// - `Value::BigInteger`, `Value::BigDecimal`
1790impl ValueConverter<f64> for Value {
1791    fn convert(&self) -> ValueResult<f64> {
1792        match self {
1793            Value::Float64(v) => Ok(*v),
1794            Value::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
1795            Value::Char(v) => Ok(*v as u32 as f64),
1796            Value::Float32(v) => Ok(*v as f64),
1797            Value::Int8(v) => Ok(*v as f64),
1798            Value::Int16(v) => Ok(*v as f64),
1799            Value::Int32(v) => Ok(*v as f64),
1800            Value::Int64(v) => Ok(*v as f64),
1801            Value::Int128(v) => Ok(*v as f64),
1802            Value::UInt8(v) => Ok(*v as f64),
1803            Value::UInt16(v) => Ok(*v as f64),
1804            Value::UInt32(v) => Ok(*v as f64),
1805            Value::UInt64(v) => Ok(*v as f64),
1806            Value::UInt128(v) => Ok(*v as f64),
1807            Value::String(s) => s
1808                .parse::<f64>()
1809                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to f64", s))),
1810            Value::Empty(_) => Err(ValueError::NoValue),
1811            Value::BigInteger(v) => Ok(v.to_f64().unwrap_or(f64::INFINITY)),
1812            Value::BigDecimal(v) => Ok(v.to_f64().unwrap_or(f64::INFINITY)),
1813            _ => Err(ValueError::ConversionFailed {
1814                from: self.data_type(),
1815                to: DataType::Float64,
1816            }),
1817        }
1818    }
1819}
1820
1821// Url
1822impl ValueGetter<Url> for Value {
1823    fn get_value(&self) -> ValueResult<Url> {
1824        self.get_url()
1825    }
1826}
1827
1828impl ValueSetter<Url> for Value {
1829    fn set_value(&mut self, value: Url) -> ValueResult<()> {
1830        self.set_url(value)
1831    }
1832}
1833
1834impl ValueConstructor<Url> for Value {
1835    fn from_type(value: Url) -> Self {
1836        Value::Url(value)
1837    }
1838}
1839
1840/// Target type `Duration` supports conversion from:
1841///
1842/// - `Value::Duration`
1843/// - `Value::String`, parsed from `<nanoseconds>ns`
1844impl ValueConverter<Duration> for Value {
1845    fn convert(&self) -> ValueResult<Duration> {
1846        match self {
1847            Value::Duration(v) => Ok(*v),
1848            Value::String(s) => parse_duration_string(s),
1849            Value::Empty(_) => Err(ValueError::NoValue),
1850            _ => Err(ValueError::ConversionFailed {
1851                from: self.data_type(),
1852                to: DataType::Duration,
1853            }),
1854        }
1855    }
1856}
1857
1858/// Target type `Url` supports conversion from:
1859///
1860/// - `Value::Url`
1861/// - `Value::String`, parsed as URL text
1862impl ValueConverter<Url> for Value {
1863    fn convert(&self) -> ValueResult<Url> {
1864        match self {
1865            Value::Url(v) => Ok(v.clone()),
1866            Value::String(s) => Url::parse(s).map_err(|e| {
1867                ValueError::ConversionError(format!("Cannot convert '{}' to Url: {}", s, e))
1868            }),
1869            Value::Empty(_) => Err(ValueError::NoValue),
1870            _ => Err(ValueError::ConversionFailed {
1871                from: self.data_type(),
1872                to: DataType::Url,
1873            }),
1874        }
1875    }
1876}
1877
1878// HashMap<String, String>
1879impl ValueGetter<HashMap<String, String>> for Value {
1880    fn get_value(&self) -> ValueResult<HashMap<String, String>> {
1881        self.get_string_map()
1882    }
1883}
1884
1885impl ValueSetter<HashMap<String, String>> for Value {
1886    fn set_value(&mut self, value: HashMap<String, String>) -> ValueResult<()> {
1887        self.set_string_map(value)
1888    }
1889}
1890
1891impl ValueConstructor<HashMap<String, String>> for Value {
1892    fn from_type(value: HashMap<String, String>) -> Self {
1893        Value::StringMap(value)
1894    }
1895}
1896
1897// serde_json::Value
1898impl ValueGetter<serde_json::Value> for Value {
1899    fn get_value(&self) -> ValueResult<serde_json::Value> {
1900        self.get_json()
1901    }
1902}
1903
1904impl ValueSetter<serde_json::Value> for Value {
1905    fn set_value(&mut self, value: serde_json::Value) -> ValueResult<()> {
1906        self.set_json(value)
1907    }
1908}
1909
1910impl ValueConstructor<serde_json::Value> for Value {
1911    fn from_type(value: serde_json::Value) -> Self {
1912        Value::Json(value)
1913    }
1914}
1915
1916/// Target type `serde_json::Value` supports conversion from:
1917///
1918/// - `Value::Json`
1919/// - `Value::String`, parsed as JSON text
1920/// - `Value::StringMap`, converted to a JSON object
1921impl ValueConverter<serde_json::Value> for Value {
1922    fn convert(&self) -> ValueResult<serde_json::Value> {
1923        match self {
1924            Value::Json(v) => Ok(v.clone()),
1925            Value::String(s) => serde_json::from_str(s)
1926                .map_err(|e| ValueError::JsonDeserializationError(e.to_string())),
1927            Value::StringMap(v) => serde_json::to_value(v)
1928                .map_err(|e| ValueError::JsonSerializationError(e.to_string())),
1929            Value::Empty(_) => Err(ValueError::NoValue),
1930            _ => Err(ValueError::ConversionFailed {
1931                from: self.data_type(),
1932                to: DataType::Json,
1933            }),
1934        }
1935    }
1936}
1937
1938impl_strict_value_converter!(
1939    /// Target type `char` supports conversion from:
1940    ///
1941    /// - `Value::Char`
1942    char,
1943    get_char
1944);
1945impl_strict_value_converter!(
1946    /// Target type `i8` supports conversion from:
1947    ///
1948    /// - `Value::Int8`
1949    i8,
1950    get_int8
1951);
1952impl_strict_value_converter!(
1953    /// Target type `i16` supports conversion from:
1954    ///
1955    /// - `Value::Int16`
1956    i16,
1957    get_int16
1958);
1959impl_strict_value_converter!(
1960    /// Target type `i128` supports conversion from:
1961    ///
1962    /// - `Value::Int128`
1963    i128,
1964    get_int128
1965);
1966/// Target type `u8` supports conversion from:
1967///
1968/// - `Value::UInt8`
1969/// - `Value::Bool`
1970/// - `Value::Char`
1971/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
1972///   `Value::Int128`
1973/// - `Value::UInt16`, `Value::UInt32`, `Value::UInt64`, `Value::UInt128`
1974/// - `Value::String`, parsed as `u8`
1975impl ValueConverter<u8> for Value {
1976    fn convert(&self) -> ValueResult<u8> {
1977        match self {
1978            Value::UInt8(v) => Ok(*v),
1979            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
1980            Value::Char(v) => {
1981                let code = range_check(*v as u32, u8::MIN as u32, u8::MAX as u32, "u8")?;
1982                Ok(code as u8)
1983            }
1984            Value::Int8(v) => {
1985                let n = range_check(*v, 0i8, i8::MAX, "u8")?;
1986                Ok(n as u8)
1987            }
1988            Value::Int16(v) => {
1989                let n = range_check(*v, u8::MIN as i16, u8::MAX as i16, "u8")?;
1990                Ok(n as u8)
1991            }
1992            Value::Int32(v) => {
1993                let n = range_check(*v, u8::MIN as i32, u8::MAX as i32, "u8")?;
1994                Ok(n as u8)
1995            }
1996            Value::Int64(v) => {
1997                let n = range_check(*v, u8::MIN as i64, u8::MAX as i64, "u8")?;
1998                Ok(n as u8)
1999            }
2000            Value::Int128(v) => {
2001                let n = range_check(*v, u8::MIN as i128, u8::MAX as i128, "u8")?;
2002                Ok(n as u8)
2003            }
2004            Value::UInt16(v) => {
2005                let n = range_check(*v, u8::MIN as u16, u8::MAX as u16, "u8")?;
2006                Ok(n as u8)
2007            }
2008            Value::UInt32(v) => {
2009                let n = range_check(*v, u8::MIN as u32, u8::MAX as u32, "u8")?;
2010                Ok(n as u8)
2011            }
2012            Value::UInt64(v) => {
2013                let n = range_check(*v, u8::MIN as u64, u8::MAX as u64, "u8")?;
2014                Ok(n as u8)
2015            }
2016            Value::UInt128(v) => {
2017                let n = range_check(*v, u8::MIN as u128, u8::MAX as u128, "u8")?;
2018                Ok(n as u8)
2019            }
2020            Value::String(s) => s
2021                .parse::<u8>()
2022                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to u8", s))),
2023            Value::Empty(_) => Err(ValueError::NoValue),
2024            _ => Err(ValueError::ConversionFailed {
2025                from: self.data_type(),
2026                to: DataType::UInt8,
2027            }),
2028        }
2029    }
2030}
2031
2032/// Target type `u16` supports conversion from:
2033///
2034/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
2035///   `Value::UInt128`
2036/// - `Value::Bool`
2037/// - `Value::Char`
2038/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
2039///   `Value::Int128`
2040/// - `Value::String`, parsed as `u16`
2041impl ValueConverter<u16> for Value {
2042    fn convert(&self) -> ValueResult<u16> {
2043        match self {
2044            Value::UInt8(v) => Ok((*v).into()),
2045            Value::UInt16(v) => Ok(*v),
2046            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
2047            Value::Char(v) => {
2048                let code = range_check(*v as u32, u16::MIN as u32, u16::MAX as u32, "u16")?;
2049                Ok(code as u16)
2050            }
2051            Value::Int8(v) => {
2052                let n = range_check(*v, 0i8, i8::MAX, "u16")?;
2053                Ok(n as u16)
2054            }
2055            Value::Int16(v) => {
2056                let n = range_check(*v, 0i16, i16::MAX, "u16")?;
2057                Ok(n as u16)
2058            }
2059            Value::Int32(v) => {
2060                let n = range_check(*v, u16::MIN as i32, u16::MAX as i32, "u16")?;
2061                Ok(n as u16)
2062            }
2063            Value::Int64(v) => {
2064                let n = range_check(*v, u16::MIN as i64, u16::MAX as i64, "u16")?;
2065                Ok(n as u16)
2066            }
2067            Value::Int128(v) => {
2068                let n = range_check(*v, u16::MIN as i128, u16::MAX as i128, "u16")?;
2069                Ok(n as u16)
2070            }
2071            Value::UInt32(v) => {
2072                let n = range_check(*v, u16::MIN as u32, u16::MAX as u32, "u16")?;
2073                Ok(n as u16)
2074            }
2075            Value::UInt64(v) => {
2076                let n = range_check(*v, u16::MIN as u64, u16::MAX as u64, "u16")?;
2077                Ok(n as u16)
2078            }
2079            Value::UInt128(v) => {
2080                let n = range_check(*v, u16::MIN as u128, u16::MAX as u128, "u16")?;
2081                Ok(n as u16)
2082            }
2083            Value::String(s) => s
2084                .parse::<u16>()
2085                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to u16", s))),
2086            Value::Empty(_) => Err(ValueError::NoValue),
2087            _ => Err(ValueError::ConversionFailed {
2088                from: self.data_type(),
2089                to: DataType::UInt16,
2090            }),
2091        }
2092    }
2093}
2094
2095/// Target type `u32` supports conversion from:
2096///
2097/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
2098///   `Value::UInt128`
2099/// - `Value::Bool`
2100/// - `Value::Char`
2101/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
2102///   `Value::Int128`
2103/// - `Value::String`, parsed as `u32`
2104impl ValueConverter<u32> for Value {
2105    fn convert(&self) -> ValueResult<u32> {
2106        match self {
2107            Value::UInt8(v) => Ok((*v).into()),
2108            Value::UInt16(v) => Ok((*v).into()),
2109            Value::UInt32(v) => Ok(*v),
2110            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
2111            Value::Char(v) => Ok(*v as u32),
2112            Value::Int8(v) => {
2113                let n = range_check(*v, 0i8, i8::MAX, "u32")?;
2114                Ok(n as u32)
2115            }
2116            Value::Int16(v) => {
2117                let n = range_check(*v, 0i16, i16::MAX, "u32")?;
2118                Ok(n as u32)
2119            }
2120            Value::Int32(v) => {
2121                let n = range_check(*v, 0i32, i32::MAX, "u32")?;
2122                Ok(n as u32)
2123            }
2124            Value::Int64(v) => {
2125                let n = range_check(*v, u32::MIN as i64, u32::MAX as i64, "u32")?;
2126                Ok(n as u32)
2127            }
2128            Value::Int128(v) => {
2129                let n = range_check(*v, u32::MIN as i128, u32::MAX as i128, "u32")?;
2130                Ok(n as u32)
2131            }
2132            Value::UInt64(v) => {
2133                let n = range_check(*v, u32::MIN as u64, u32::MAX as u64, "u32")?;
2134                Ok(n as u32)
2135            }
2136            Value::UInt128(v) => {
2137                let n = range_check(*v, u32::MIN as u128, u32::MAX as u128, "u32")?;
2138                Ok(n as u32)
2139            }
2140            Value::String(s) => s
2141                .parse::<u32>()
2142                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to u32", s))),
2143            Value::Empty(_) => Err(ValueError::NoValue),
2144            _ => Err(ValueError::ConversionFailed {
2145                from: self.data_type(),
2146                to: DataType::UInt32,
2147            }),
2148        }
2149    }
2150}
2151
2152/// Target type `u64` supports conversion from:
2153///
2154/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
2155///   `Value::UInt128`
2156/// - `Value::Bool`
2157/// - `Value::Char`
2158/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
2159///   `Value::Int128`
2160/// - `Value::String`, parsed as `u64`
2161impl ValueConverter<u64> for Value {
2162    fn convert(&self) -> ValueResult<u64> {
2163        match self {
2164            Value::UInt8(v) => Ok((*v).into()),
2165            Value::UInt16(v) => Ok((*v).into()),
2166            Value::UInt32(v) => Ok((*v).into()),
2167            Value::UInt64(v) => Ok(*v),
2168            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
2169            Value::Char(v) => Ok((*v as u32).into()),
2170            Value::Int8(v) => {
2171                let n = range_check(*v, 0i8, i8::MAX, "u64")?;
2172                Ok(n as u64)
2173            }
2174            Value::Int16(v) => {
2175                let n = range_check(*v, 0i16, i16::MAX, "u64")?;
2176                Ok(n as u64)
2177            }
2178            Value::Int32(v) => {
2179                let n = range_check(*v, 0i32, i32::MAX, "u64")?;
2180                Ok(n as u64)
2181            }
2182            Value::Int64(v) => {
2183                let n = range_check(*v, 0i64, i64::MAX, "u64")?;
2184                Ok(n as u64)
2185            }
2186            Value::Int128(v) => {
2187                let n = range_check(*v, 0i128, u64::MAX as i128, "u64")?;
2188                Ok(n as u64)
2189            }
2190            Value::UInt128(v) => {
2191                let n = range_check(*v, u64::MIN as u128, u64::MAX as u128, "u64")?;
2192                Ok(n as u64)
2193            }
2194            Value::String(s) => s
2195                .parse::<u64>()
2196                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to u64", s))),
2197            Value::Empty(_) => Err(ValueError::NoValue),
2198            _ => Err(ValueError::ConversionFailed {
2199                from: self.data_type(),
2200                to: DataType::UInt64,
2201            }),
2202        }
2203    }
2204}
2205
2206/// Target type `u128` supports conversion from:
2207///
2208/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
2209///   `Value::UInt128`
2210/// - `Value::Bool`
2211/// - `Value::Char`
2212/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
2213///   `Value::Int128`
2214/// - `Value::String`, parsed as `u128`
2215impl ValueConverter<u128> for Value {
2216    fn convert(&self) -> ValueResult<u128> {
2217        match self {
2218            Value::UInt8(v) => Ok((*v).into()),
2219            Value::UInt16(v) => Ok((*v).into()),
2220            Value::UInt32(v) => Ok((*v).into()),
2221            Value::UInt64(v) => Ok((*v).into()),
2222            Value::UInt128(v) => Ok(*v),
2223            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
2224            Value::Char(v) => Ok((*v as u32).into()),
2225            Value::Int8(v) => {
2226                let n = range_check(*v, 0i8, i8::MAX, "u128")?;
2227                Ok(n as u128)
2228            }
2229            Value::Int16(v) => {
2230                let n = range_check(*v, 0i16, i16::MAX, "u128")?;
2231                Ok(n as u128)
2232            }
2233            Value::Int32(v) => {
2234                let n = range_check(*v, 0i32, i32::MAX, "u128")?;
2235                Ok(n as u128)
2236            }
2237            Value::Int64(v) => {
2238                let n = range_check(*v, 0i64, i64::MAX, "u128")?;
2239                Ok(n as u128)
2240            }
2241            Value::Int128(v) => {
2242                let n = range_check(*v, 0i128, i128::MAX, "u128")?;
2243                Ok(n as u128)
2244            }
2245            Value::String(s) => s.parse::<u128>().map_err(|_| {
2246                ValueError::ConversionError(format!("Cannot convert '{}' to u128", s))
2247            }),
2248            Value::Empty(_) => Err(ValueError::NoValue),
2249            _ => Err(ValueError::ConversionFailed {
2250                from: self.data_type(),
2251                to: DataType::UInt128,
2252            }),
2253        }
2254    }
2255}
2256
2257/// Target type `f32` supports conversion from:
2258///
2259/// - `Value::Float32`, `Value::Float64`
2260/// - `Value::Bool`
2261/// - `Value::Char`
2262/// - `Value::Int8`, `Value::Int16`, `Value::Int32`, `Value::Int64`,
2263///   `Value::Int128`
2264/// - `Value::UInt8`, `Value::UInt16`, `Value::UInt32`, `Value::UInt64`,
2265///   `Value::UInt128`
2266/// - `Value::String`, parsed as `f32`
2267/// - `Value::BigInteger`, `Value::BigDecimal`
2268impl ValueConverter<f32> for Value {
2269    fn convert(&self) -> ValueResult<f32> {
2270        match self {
2271            Value::Float32(v) => Ok(*v),
2272            Value::Float64(v) => {
2273                if v.is_nan() || v.is_infinite() {
2274                    Ok(*v as f32)
2275                } else {
2276                    let n = range_check(*v, f32::MIN as f64, f32::MAX as f64, "f32")?;
2277                    Ok(n as f32)
2278                }
2279            }
2280            Value::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
2281            Value::Char(v) => Ok(*v as u32 as f32),
2282            Value::Int8(v) => Ok(*v as f32),
2283            Value::Int16(v) => Ok(*v as f32),
2284            Value::Int32(v) => Ok(*v as f32),
2285            Value::Int64(v) => Ok(*v as f32),
2286            Value::Int128(v) => Ok(*v as f32),
2287            Value::UInt8(v) => Ok(*v as f32),
2288            Value::UInt16(v) => Ok(*v as f32),
2289            Value::UInt32(v) => Ok(*v as f32),
2290            Value::UInt64(v) => Ok(*v as f32),
2291            Value::UInt128(v) => Ok(*v as f32),
2292            Value::String(s) => s
2293                .parse::<f32>()
2294                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to f32", s))),
2295            Value::Empty(_) => Err(ValueError::NoValue),
2296            Value::BigInteger(v) => Ok(v.to_f32().unwrap_or(f32::INFINITY)),
2297            Value::BigDecimal(v) => Ok(v.to_f32().unwrap_or(f32::INFINITY)),
2298            _ => Err(ValueError::ConversionFailed {
2299                from: self.data_type(),
2300                to: DataType::Float32,
2301            }),
2302        }
2303    }
2304}
2305impl_strict_value_converter!(
2306    /// Target type `NaiveDate` supports conversion from:
2307    ///
2308    /// - `Value::Date`
2309    NaiveDate,
2310    get_date
2311);
2312impl_strict_value_converter!(
2313    /// Target type `NaiveTime` supports conversion from:
2314    ///
2315    /// - `Value::Time`
2316    NaiveTime,
2317    get_time
2318);
2319impl_strict_value_converter!(
2320    /// Target type `NaiveDateTime` supports conversion from:
2321    ///
2322    /// - `Value::DateTime`
2323    NaiveDateTime,
2324    get_datetime
2325);
2326impl_strict_value_converter!(
2327    /// Target type `DateTime<Utc>` supports conversion from:
2328    ///
2329    /// - `Value::Instant`
2330    DateTime<Utc>,
2331    get_instant
2332);
2333impl_strict_value_converter!(
2334    /// Target type `BigInt` supports conversion from:
2335    ///
2336    /// - `Value::BigInteger`
2337    BigInt,
2338    get_biginteger
2339);
2340impl_strict_value_converter!(
2341    /// Target type `BigDecimal` supports conversion from:
2342    ///
2343    /// - `Value::BigDecimal`
2344    BigDecimal,
2345    get_bigdecimal
2346);
2347impl_strict_value_converter!(
2348    /// Target type `isize` supports conversion from:
2349    ///
2350    /// - `Value::IntSize`
2351    isize,
2352    get_intsize
2353);
2354impl_strict_value_converter!(
2355    /// Target type `usize` supports conversion from:
2356    ///
2357    /// - `Value::UIntSize`
2358    usize,
2359    get_uintsize
2360);
2361impl_strict_value_converter!(
2362    /// Target type `HashMap<String, String>` supports conversion from:
2363    ///
2364    /// - `Value::StringMap`
2365    HashMap<String, String>,
2366    get_string_map
2367);