prism3_value/
value.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025.
4 *    3-Prism 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::{Deserialize, Serialize};
22
23use prism3_core::lang::DataType;
24
25use super::error::{ValueError, ValueResult};
26
27/// Single value container
28///
29/// Uses an enum to represent different types of values, providing type-safe value storage and access.
30///
31/// # Features
32///
33/// - Zero-cost abstraction with compile-time type checking
34/// - Supports multiple basic data types
35/// - Provides two sets of APIs for type checking and type conversion
36/// - Automatic memory management
37///
38/// # Example
39///
40/// ```rust,ignore
41/// use common_rs::util::value::Value;
42///
43/// // Create an integer value
44/// let value = Value::Int32(42);
45/// assert_eq!(value.get_int32().unwrap(), 42);
46///
47/// // Type conversion
48/// let converted = value.as_int64().unwrap();
49/// assert_eq!(converted, 42i64);
50///
51/// // String value
52/// let text = Value::String("hello".to_string());
53/// assert_eq!(text.get_string().unwrap(), "hello");
54/// ```
55///
56/// # Author
57///
58/// Haixing Hu
59///
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub enum Value {
62    /// Empty value (has type but no value)
63    Empty(DataType),
64    /// Boolean value
65    Bool(bool),
66    /// Character value
67    Char(char),
68    /// 8-bit signed integer
69    Int8(i8),
70    /// 16-bit signed integer
71    Int16(i16),
72    /// 32-bit signed integer
73    Int32(i32),
74    /// 64-bit signed integer
75    Int64(i64),
76    /// 128-bit signed integer
77    Int128(i128),
78    /// 8-bit unsigned integer
79    UInt8(u8),
80    /// 16-bit unsigned integer
81    UInt16(u16),
82    /// 32-bit unsigned integer
83    UInt32(u32),
84    /// 64-bit unsigned integer
85    UInt64(u64),
86    /// 128-bit unsigned integer
87    UInt128(u128),
88    /// 32-bit floating point number
89    Float32(f32),
90    /// 64-bit floating point number
91    Float64(f64),
92    /// String
93    String(String),
94    /// Date
95    Date(NaiveDate),
96    /// Time
97    Time(NaiveTime),
98    /// Date and time
99    DateTime(NaiveDateTime),
100    /// UTC instant
101    Instant(DateTime<Utc>),
102    /// Big integer type
103    BigInteger(BigInt),
104    /// Big decimal type
105    BigDecimal(BigDecimal),
106}
107
108// ============================================================================
109// Getter method generation macro
110// ============================================================================
111
112/// Unified getter generation macro
113///
114/// Supports two modes:
115/// 1. `copy:` - For types implementing the Copy trait, directly returns the value
116/// 2. `ref:` - For non-Copy types, returns a reference
117///
118/// # Documentation Comment Support
119///
120/// The macro automatically extracts preceding documentation comments, so you can add `///` comments before macro invocations.
121///
122/// # Author
123///
124/// Haixing Hu
125///
126macro_rules! impl_get_value {
127    // Copy type: directly dereference and return
128    ($(#[$attr:meta])* copy: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
129        $(#[$attr])*
130        pub fn $method(&self) -> ValueResult<$type> {
131            match self {
132                Value::$variant(v) => Ok(*v),
133                Value::Empty(_) => Err(ValueError::NoValue),
134                _ => Err(ValueError::TypeMismatch {
135                    expected: $data_type,
136                    actual: self.data_type(),
137                }),
138            }
139        }
140    };
141
142    // Reference type: use conversion function to return reference, fixing lifetime issues
143    ($(#[$attr:meta])* ref: $method:ident, $variant:ident, $ret_type:ty, $data_type:expr, $conversion:expr) => {
144        $(#[$attr])*
145        pub fn $method(&self) -> ValueResult<$ret_type> {
146            match self {
147                Value::$variant(v) => {
148                    let conv_fn: fn(&_) -> $ret_type = $conversion;
149                    Ok(conv_fn(v))
150                },
151                Value::Empty(_) => Err(ValueError::NoValue),
152                _ => Err(ValueError::TypeMismatch {
153                    expected: $data_type,
154                    actual: self.data_type(),
155                }),
156            }
157        }
158    };
159}
160
161/// Unified setter generation macro
162///
163/// Supports two modes:
164/// 1. `copy:` - For types implementing the Copy trait, directly sets the value
165/// 2. `owned:` - For non-Copy types, requires owning the value
166///
167/// # Documentation Comment Support
168///
169/// The macro automatically extracts preceding documentation comments, so you can add `///` comments before macro invocations.
170///
171/// # Author
172///
173/// Haixing Hu
174///
175macro_rules! impl_set_value {
176    // Copy type: directly set the value
177    ($(#[$attr:meta])* copy: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
178        $(#[$attr])*
179        pub fn $method(&mut self, value: $type) -> ValueResult<()> {
180            *self = Value::$variant(value);
181            Ok(())
182        }
183    };
184
185    // Owned type: set the owned value
186    ($(#[$attr:meta])* owned: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
187        $(#[$attr])*
188        pub fn $method(&mut self, value: $type) -> ValueResult<()> {
189            *self = Value::$variant(value);
190            Ok(())
191        }
192    };
193}
194
195impl Value {
196    /// Generic constructor method
197    ///
198    /// Creates a `Value` from any supported type, avoiding direct use of enum variants.
199    ///
200    /// # Type Parameters
201    ///
202    /// * `T` - The type of the value to wrap
203    ///
204    /// # Returns
205    ///
206    /// Returns a `Value` wrapping the given value
207    ///
208    /// # Example
209    ///
210    /// ```rust,ignore
211    /// use crate::util::value::Value;
212    ///
213    /// // Basic types
214    /// let v = Value::new(42i32);
215    /// assert_eq!(v.get_int32().unwrap(), 42);
216    ///
217    /// let v = Value::new(true);
218    /// assert_eq!(v.get_bool().unwrap(), true);
219    ///
220    /// // String
221    /// let v = Value::new("hello".to_string());
222    /// assert_eq!(v.get_string().unwrap(), "hello");
223    /// ```
224    pub fn new<T>(value: T) -> Self
225    where
226        Self: ValueConstructor<T>,
227    {
228        <Self as ValueConstructor<T>>::from_type(value)
229    }
230
231    /// Generic getter method
232    ///
233    /// Automatically selects the correct getter method based on the target type, performing strict type checking.
234    ///
235    /// # Type Parameters
236    ///
237    /// * `T` - The target type to retrieve
238    ///
239    /// # Returns
240    ///
241    /// If types match, returns the value of the corresponding type; otherwise returns an error
242    ///
243    /// # Example
244    ///
245    /// ```rust,ignore
246    /// use crate::util::value::Value;
247    ///
248    /// let value = Value::Int32(42);
249    ///
250    /// // Through type inference
251    /// let num: i32 = value.get().unwrap();
252    /// assert_eq!(num, 42);
253    ///
254    /// // Explicitly specify type parameter
255    /// let num = value.get::<i32>().unwrap();
256    /// assert_eq!(num, 42);
257    ///
258    /// // Different type
259    /// let text = Value::String("hello".to_string());
260    /// let s: String = text.get().unwrap();
261    /// assert_eq!(s, "hello");
262    ///
263    /// // Boolean value
264    /// let flag = Value::Bool(true);
265    /// let b: bool = flag.get().unwrap();
266    /// assert_eq!(b, true);
267    /// ```
268    pub fn get<T>(&self) -> ValueResult<T>
269    where
270        Self: ValueGetter<T>,
271    {
272        <Self as ValueGetter<T>>::get_value(self)
273    }
274
275    /// Generic setter method
276    ///
277    /// Automatically selects the correct setter method based on the target type, performing strict type checking.
278    ///
279    /// # Type Parameters
280    ///
281    /// * `T` - The target type to set
282    ///
283    /// # Parameters
284    ///
285    /// * `value` - The value to set
286    ///
287    /// # Returns
288    ///
289    /// If setting succeeds, returns `Ok(())`; otherwise returns an error
290    ///
291    /// # Example
292    ///
293    /// ```rust,ignore
294    /// use crate::util::value::Value;
295    ///
296    /// let mut value = Value::Empty(DataType::Int32);
297    ///
298    /// // Through type inference
299    /// value.set(42i32).unwrap();
300    /// assert_eq!(value.get_int32().unwrap(), 42);
301    ///
302    /// // Explicitly specify type parameter
303    /// value.set::<i32>(100).unwrap();
304    /// assert_eq!(value.get_int32().unwrap(), 100);
305    ///
306    /// // String type
307    /// let mut text = Value::Empty(DataType::String);
308    /// text.set("hello".to_string()).unwrap();
309    /// assert_eq!(text.get_string().unwrap(), "hello");
310    /// ```
311    pub fn set<T>(&mut self, value: T) -> ValueResult<()>
312    where
313        Self: ValueSetter<T>,
314    {
315        <Self as ValueSetter<T>>::set_value(self, value)
316    }
317
318    /// Get the data type of the value
319    ///
320    /// # Returns
321    ///
322    /// Returns the data type corresponding to this value
323    ///
324    /// # Example
325    ///
326    /// ```rust,ignore
327    /// use crate::util::value::{Value, DataType};
328    ///
329    /// let value = Value::Int32(42);
330    /// assert_eq!(value.data_type(), DataType::Int32);
331    ///
332    /// let empty = Value::Empty(DataType::String);
333    /// assert_eq!(empty.data_type(), DataType::String);
334    /// ```
335    pub fn data_type(&self) -> DataType {
336        match self {
337            Value::Empty(dt) => *dt,
338            Value::Bool(_) => DataType::Bool,
339            Value::Char(_) => DataType::Char,
340            Value::Int8(_) => DataType::Int8,
341            Value::Int16(_) => DataType::Int16,
342            Value::Int32(_) => DataType::Int32,
343            Value::Int64(_) => DataType::Int64,
344            Value::Int128(_) => DataType::Int128,
345            Value::UInt8(_) => DataType::UInt8,
346            Value::UInt16(_) => DataType::UInt16,
347            Value::UInt32(_) => DataType::UInt32,
348            Value::UInt64(_) => DataType::UInt64,
349            Value::UInt128(_) => DataType::UInt128,
350            Value::Float32(_) => DataType::Float32,
351            Value::Float64(_) => DataType::Float64,
352            Value::String(_) => DataType::String,
353            Value::Date(_) => DataType::Date,
354            Value::Time(_) => DataType::Time,
355            Value::DateTime(_) => DataType::DateTime,
356            Value::Instant(_) => DataType::Instant,
357            Value::BigInteger(_) => DataType::BigInteger,
358            Value::BigDecimal(_) => DataType::BigDecimal,
359        }
360    }
361
362    /// Check if the value is empty
363    ///
364    /// # Returns
365    ///
366    /// Returns `true` if the value is empty
367    ///
368    /// # Example
369    ///
370    /// ```rust,ignore
371    /// use crate::util::value::{Value, DataType};
372    ///
373    /// let value = Value::Int32(42);
374    /// assert!(!value.is_empty());
375    ///
376    /// let empty = Value::Empty(DataType::String);
377    /// assert!(empty.is_empty());
378    /// ```
379    pub fn is_empty(&self) -> bool {
380        matches!(self, Value::Empty(_))
381    }
382
383    /// Clear the value while preserving the type
384    ///
385    /// Sets the current value to empty but retains its data type.
386    ///
387    /// # Example
388    ///
389    /// ```rust,ignore
390    /// use crate::util::value::{Value, DataType};
391    ///
392    /// let mut value = Value::Int32(42);
393    /// value.clear();
394    /// assert!(value.is_empty());
395    /// assert_eq!(value.data_type(), DataType::Int32);
396    /// ```
397    pub fn clear(&mut self) {
398        let dt = self.data_type();
399        *self = Value::Empty(dt);
400    }
401
402    /// Set the data type
403    ///
404    /// If the new type differs from the current type, clears the value and sets the new type.
405    ///
406    /// # Parameters
407    ///
408    /// * `data_type` - The data type to set
409    ///
410    /// # Example
411    ///
412    /// ```rust,ignore
413    /// use crate::util::value::{Value, DataType};
414    ///
415    /// let mut value = Value::Int32(42);
416    /// value.set_type(DataType::String);
417    /// assert!(value.is_empty());
418    /// assert_eq!(value.data_type(), DataType::String);
419    /// ```
420    pub fn set_type(&mut self, data_type: DataType) {
421        if self.data_type() != data_type {
422            *self = Value::Empty(data_type);
423        }
424    }
425
426    // ========================================================================
427    // Type-checking getters (strict type matching)
428    // ========================================================================
429
430    impl_get_value! {
431        /// Get boolean value
432        ///
433        /// # Returns
434        ///
435        /// If types match, returns the boolean value; otherwise returns an error
436        ///
437        /// # Example
438        ///
439        /// ```rust,ignore
440        /// use crate::util::value::Value;
441        ///
442        /// let value = Value::Bool(true);
443        /// assert_eq!(value.get_bool().unwrap(), true);
444        /// ```
445        copy: get_bool, Bool, bool, DataType::Bool
446    }
447
448    impl_get_value! {
449        /// Get character value
450        ///
451        /// # Returns
452        ///
453        /// If types match, returns the character value; otherwise returns an error
454        ///
455        /// # Example
456        ///
457        /// ```rust,ignore
458        /// use crate::util::value::Value;
459        ///
460        /// let value = Value::Char('A');
461        /// assert_eq!(value.get_char().unwrap(), 'A');
462        /// ```
463        copy: get_char, Char, char, DataType::Char
464    }
465
466    impl_get_value! {
467        /// Get int8 value
468        ///
469        /// # Returns
470        ///
471        /// If types match, returns the int8 value; otherwise returns an error
472        copy: get_int8, Int8, i8, DataType::Int8
473    }
474
475    impl_get_value! {
476        /// Get int16 value
477        ///
478        /// # Returns
479        ///
480        /// If types match, returns the int16 value; otherwise returns an error
481        copy: get_int16, Int16, i16, DataType::Int16
482    }
483
484    impl_get_value! {
485        /// Get int32 value
486        ///
487        /// # Returns
488        ///
489        /// If types match, returns the int32 value; otherwise returns an error
490        copy: get_int32, Int32, i32, DataType::Int32
491    }
492
493    impl_get_value! {
494        /// Get int64 value
495        ///
496        /// # Returns
497        ///
498        /// If types match, returns the int64 value; otherwise returns an error
499        copy: get_int64, Int64, i64, DataType::Int64
500    }
501
502    impl_get_value! {
503        /// Get int128 value
504        ///
505        /// # Returns
506        ///
507        /// If types match, returns the int128 value; otherwise returns an error
508        copy: get_int128, Int128, i128, DataType::Int128
509    }
510
511    impl_get_value! {
512        /// Get uint8 value
513        ///
514        /// # Returns
515        ///
516        /// If types match, returns the uint8 value; otherwise returns an error
517        copy: get_uint8, UInt8, u8, DataType::UInt8
518    }
519
520    impl_get_value! {
521        /// Get uint16 value
522        ///
523        /// # Returns
524        ///
525        /// If types match, returns the uint16 value; otherwise returns an error
526        copy: get_uint16, UInt16, u16, DataType::UInt16
527    }
528
529    impl_get_value! {
530        /// Get uint32 value
531        ///
532        /// # Returns
533        ///
534        /// If types match, returns the uint32 value; otherwise returns an error
535        copy: get_uint32, UInt32, u32, DataType::UInt32
536    }
537
538    impl_get_value! {
539        /// Get uint64 value
540        ///
541        /// # Returns
542        ///
543        /// If types match, returns the uint64 value; otherwise returns an error
544        copy: get_uint64, UInt64, u64, DataType::UInt64
545    }
546
547    impl_get_value! {
548        /// Get uint128 value
549        ///
550        /// # Returns
551        ///
552        /// If types match, returns the uint128 value; otherwise returns an error
553        copy: get_uint128, UInt128, u128, DataType::UInt128
554    }
555
556    impl_get_value! {
557        /// Get float32 value
558        ///
559        /// # Returns
560        ///
561        /// If types match, returns the float32 value; otherwise returns an error
562        copy: get_float32, Float32, f32, DataType::Float32
563    }
564
565    impl_get_value! {
566        /// Get float64 value
567        ///
568        /// # Returns
569        ///
570        /// If types match, returns the float64 value; otherwise returns an error
571        copy: get_float64, Float64, f64, DataType::Float64
572    }
573
574    impl_get_value! {
575        /// Get string reference
576        ///
577        /// # Returns
578        ///
579        /// If types match, returns a reference to the string; otherwise returns an error
580        ///
581        /// # Example
582        ///
583        /// ```rust,ignore
584        /// use crate::util::value::Value;
585        ///
586        /// let value = Value::String("hello".to_string());
587        /// assert_eq!(value.get_string().unwrap(), "hello");
588        /// ```
589        ref: get_string, String, &str, DataType::String, |s: &String| s.as_str()
590    }
591
592    impl_get_value! {
593        /// Get date value
594        ///
595        /// # Returns
596        ///
597        /// If types match, returns the date value; otherwise returns an error
598        copy: get_date, Date, NaiveDate, DataType::Date
599    }
600
601    impl_get_value! {
602        /// Get time value
603        ///
604        /// # Returns
605        ///
606        /// If types match, returns the time value; otherwise returns an error
607        copy: get_time, Time, NaiveTime, DataType::Time
608    }
609
610    impl_get_value! {
611        /// Get datetime value
612        ///
613        /// # Returns
614        ///
615        /// If types match, returns the datetime value; otherwise returns an error
616        copy: get_datetime, DateTime, NaiveDateTime, DataType::DateTime
617    }
618
619    impl_get_value! {
620        /// Get UTC instant value
621        ///
622        /// # Returns
623        ///
624        /// If types match, returns the UTC instant value; otherwise returns an error
625        copy: get_instant, Instant, DateTime<Utc>, DataType::Instant
626    }
627
628    impl_get_value! {
629        /// Get big integer value
630        ///
631        /// # Returns
632        ///
633        /// If types match, returns the big integer value; otherwise returns an error
634        ///
635        /// # Example
636        ///
637        /// ```rust,ignore
638        /// use crate::util::value::Value;
639        /// use num_bigint::BigInt;
640        ///
641        /// let value = Value::BigInteger(BigInt::from(123456789));
642        /// assert_eq!(value.get_biginteger().unwrap(), BigInt::from(123456789));
643        /// ```
644        ref: get_biginteger, BigInteger, BigInt, DataType::BigInteger, |v: &BigInt| v.clone()
645    }
646
647    impl_get_value! {
648        /// Get big decimal value
649        ///
650        /// # Returns
651        ///
652        /// If types match, returns the big decimal value; otherwise returns an error
653        ///
654        /// # Example
655        ///
656        /// ```rust,ignore
657        /// use crate::util::value::Value;
658        /// use bigdecimal::BigDecimal;
659        ///
660        /// let value = Value::BigDecimal(BigDecimal::from(123.456));
661        /// assert_eq!(value.get_bigdecimal().unwrap(), BigDecimal::from(123.456));
662        /// ```
663        ref: get_bigdecimal, BigDecimal, BigDecimal, DataType::BigDecimal, |v: &BigDecimal| v.clone()
664    }
665
666    // ========================================================================
667    // Type conversion getters (attempt conversion)
668    // ========================================================================
669
670    /// Convert to boolean value
671    ///
672    /// # Returns
673    ///
674    /// Attempts to convert the value to a boolean, supporting conversion from various types
675    ///
676    /// # Example
677    ///
678    /// ```rust,ignore
679    /// use crate::util::value::Value;
680    ///
681    /// let value = Value::Int32(1);
682    /// assert_eq!(value.as_bool().unwrap(), true);
683    ///
684    /// let value = Value::String("true".to_string());
685    /// assert_eq!(value.as_bool().unwrap(), true);
686    /// ```
687    pub fn as_bool(&self) -> ValueResult<bool> {
688        match self {
689            Value::Bool(v) => Ok(*v),
690            Value::Int8(v) => Ok(*v != 0),
691            Value::Int16(v) => Ok(*v != 0),
692            Value::Int32(v) => Ok(*v != 0),
693            Value::Int64(v) => Ok(*v != 0),
694            Value::Int128(v) => Ok(*v != 0),
695            Value::UInt8(v) => Ok(*v != 0),
696            Value::UInt16(v) => Ok(*v != 0),
697            Value::UInt32(v) => Ok(*v != 0),
698            Value::UInt64(v) => Ok(*v != 0),
699            Value::UInt128(v) => Ok(*v != 0),
700            Value::String(s) => s.parse::<bool>().map_err(|_| {
701                ValueError::ConversionError(format!("Cannot convert '{}' to boolean", s))
702            }),
703            Value::Empty(_) => Err(ValueError::NoValue),
704            _ => Err(ValueError::ConversionFailed {
705                from: self.data_type(),
706                to: DataType::Bool,
707            }),
708        }
709    }
710
711    /// Convert to int32 value
712    ///
713    /// # Returns
714    ///
715    /// Attempts to convert the value to i32, supporting conversion from various types
716    ///
717    /// # Example
718    ///
719    /// ```rust,ignore
720    /// use crate::util::value::Value;
721    ///
722    /// let value = Value::Int8(42);
723    /// assert_eq!(value.as_int32().unwrap(), 42);
724    ///
725    /// let value = Value::String("123".to_string());
726    /// assert_eq!(value.as_int32().unwrap(), 123);
727    /// ```
728    pub fn as_int32(&self) -> ValueResult<i32> {
729        match self {
730            Value::Int32(v) => Ok(*v),
731            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
732            Value::Char(v) => Ok(*v as i32),
733            Value::Int8(v) => Ok(*v as i32),
734            Value::Int16(v) => Ok(*v as i32),
735            Value::Int64(v) => (*v)
736                .try_into()
737                .map_err(|_| ValueError::ConversionError("i64 value out of i32 range".to_string())),
738            Value::Int128(v) => (*v).try_into().map_err(|_| {
739                ValueError::ConversionError("i128 value out of i32 range".to_string())
740            }),
741            Value::UInt8(v) => Ok(*v as i32),
742            Value::UInt16(v) => Ok(*v as i32),
743            Value::UInt32(v) => (*v)
744                .try_into()
745                .map_err(|_| ValueError::ConversionError("u32 value out of i32 range".to_string())),
746            Value::UInt64(v) => (*v)
747                .try_into()
748                .map_err(|_| ValueError::ConversionError("u64 value out of i32 range".to_string())),
749            Value::UInt128(v) => (*v).try_into().map_err(|_| {
750                ValueError::ConversionError("u128 value out of i32 range".to_string())
751            }),
752            Value::Float32(v) => Ok(*v as i32),
753            Value::Float64(v) => Ok(*v as i32),
754            Value::String(s) => s
755                .parse::<i32>()
756                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to i32", s))),
757            Value::Empty(_) => Err(ValueError::NoValue),
758            Value::BigInteger(v) => v.to_i32().ok_or_else(|| {
759                ValueError::ConversionError("BigInteger value out of i32 range".to_string())
760            }),
761            Value::BigDecimal(v) => v.to_i32().ok_or_else(|| {
762                ValueError::ConversionError(
763                    "BigDecimal value cannot be converted to i32".to_string(),
764                )
765            }),
766            _ => Err(ValueError::ConversionFailed {
767                from: self.data_type(),
768                to: DataType::Int32,
769            }),
770        }
771    }
772
773    /// Convert to int64 value
774    ///
775    /// # Returns
776    ///
777    /// Attempts to convert the value to i64, supporting conversion from various types
778    ///
779    /// # Example
780    ///
781    /// ```rust,ignore
782    /// use crate::util::value::Value;
783    ///
784    /// let value = Value::Int32(42);
785    /// assert_eq!(value.as_int64().unwrap(), 42i64);
786    ///
787    /// let value = Value::Float64(123.456);
788    /// assert_eq!(value.as_int64().unwrap(), 123i64);
789    /// ```
790    pub fn as_int64(&self) -> ValueResult<i64> {
791        match self {
792            Value::Int64(v) => Ok(*v),
793            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
794            Value::Char(v) => Ok(*v as i64),
795            Value::Int8(v) => Ok(*v as i64),
796            Value::Int16(v) => Ok(*v as i64),
797            Value::Int32(v) => Ok(*v as i64),
798            Value::Int128(v) => (*v).try_into().map_err(|_| {
799                ValueError::ConversionError("i128 value out of i64 range".to_string())
800            }),
801            Value::UInt8(v) => Ok(*v as i64),
802            Value::UInt16(v) => Ok(*v as i64),
803            Value::UInt32(v) => Ok(*v as i64),
804            Value::UInt64(v) => (*v)
805                .try_into()
806                .map_err(|_| ValueError::ConversionError("u64 value out of i64 range".to_string())),
807            Value::UInt128(v) => (*v).try_into().map_err(|_| {
808                ValueError::ConversionError("u128 value out of i64 range".to_string())
809            }),
810            Value::Float32(v) => Ok(*v as i64),
811            Value::Float64(v) => Ok(*v as i64),
812            Value::String(s) => s
813                .parse::<i64>()
814                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to i64", s))),
815            Value::Empty(_) => Err(ValueError::NoValue),
816            Value::BigInteger(v) => v.to_i64().ok_or_else(|| {
817                ValueError::ConversionError("BigInteger value out of i64 range".to_string())
818            }),
819            Value::BigDecimal(v) => v.to_i64().ok_or_else(|| {
820                ValueError::ConversionError(
821                    "BigDecimal value cannot be converted to i64".to_string(),
822                )
823            }),
824            _ => Err(ValueError::ConversionFailed {
825                from: self.data_type(),
826                to: DataType::Int64,
827            }),
828        }
829    }
830
831    /// Convert to float64 value
832    ///
833    /// # Returns
834    ///
835    /// Attempts to convert the value to f64, supporting conversion from various types
836    ///
837    /// # Example
838    ///
839    /// ```rust,ignore
840    /// use crate::util::value::Value;
841    ///
842    /// let value = Value::Int32(42);
843    /// assert_eq!(value.as_float64().unwrap(), 42.0);
844    ///
845    /// let value = Value::Bool(true);
846    /// assert_eq!(value.as_float64().unwrap(), 1.0);
847    /// ```
848    pub fn as_float64(&self) -> ValueResult<f64> {
849        match self {
850            Value::Float64(v) => Ok(*v),
851            Value::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
852            Value::Char(v) => Ok(*v as u32 as f64),
853            Value::Float32(v) => Ok(*v as f64),
854            Value::Int8(v) => Ok(*v as f64),
855            Value::Int16(v) => Ok(*v as f64),
856            Value::Int32(v) => Ok(*v as f64),
857            Value::Int64(v) => Ok(*v as f64),
858            Value::Int128(v) => Ok(*v as f64),
859            Value::UInt8(v) => Ok(*v as f64),
860            Value::UInt16(v) => Ok(*v as f64),
861            Value::UInt32(v) => Ok(*v as f64),
862            Value::UInt64(v) => Ok(*v as f64),
863            Value::UInt128(v) => Ok(*v as f64),
864            Value::String(s) => s
865                .parse::<f64>()
866                .map_err(|_| ValueError::ConversionError(format!("Cannot convert '{}' to f64", s))),
867            Value::Empty(_) => Err(ValueError::NoValue),
868            Value::BigInteger(v) => v.to_f64().ok_or_else(|| {
869                ValueError::ConversionError(
870                    "BigInteger value cannot be converted to f64".to_string(),
871                )
872            }),
873            Value::BigDecimal(v) => v.to_f64().ok_or_else(|| {
874                ValueError::ConversionError(
875                    "BigDecimal value cannot be converted to f64".to_string(),
876                )
877            }),
878            _ => Err(ValueError::ConversionFailed {
879                from: self.data_type(),
880                to: DataType::Float64,
881            }),
882        }
883    }
884
885    /// Convert to string
886    ///
887    /// # Returns
888    ///
889    /// Converts the value to its string representation
890    ///
891    /// # Example
892    ///
893    /// ```rust,ignore
894    /// use crate::util::value::Value;
895    ///
896    /// let value = Value::Int32(42);
897    /// assert_eq!(value.as_string().unwrap(), "42");
898    ///
899    /// let value = Value::Bool(true);
900    /// assert_eq!(value.as_string().unwrap(), "true");
901    /// ```
902    pub fn as_string(&self) -> ValueResult<String> {
903        match self {
904            Value::String(v) => Ok(v.clone()),
905            Value::Bool(v) => Ok(v.to_string()),
906            Value::Char(v) => Ok(v.to_string()),
907            Value::Int8(v) => Ok(v.to_string()),
908            Value::Int16(v) => Ok(v.to_string()),
909            Value::Int32(v) => Ok(v.to_string()),
910            Value::Int64(v) => Ok(v.to_string()),
911            Value::Int128(v) => Ok(v.to_string()),
912            Value::UInt8(v) => Ok(v.to_string()),
913            Value::UInt16(v) => Ok(v.to_string()),
914            Value::UInt32(v) => Ok(v.to_string()),
915            Value::UInt64(v) => Ok(v.to_string()),
916            Value::UInt128(v) => Ok(v.to_string()),
917            Value::Float32(v) => Ok(v.to_string()),
918            Value::Float64(v) => Ok(v.to_string()),
919            Value::Date(v) => Ok(v.to_string()),
920            Value::Time(v) => Ok(v.to_string()),
921            Value::DateTime(v) => Ok(v.to_string()),
922            Value::Instant(v) => Ok(v.to_rfc3339()),
923            Value::BigInteger(v) => Ok(v.to_string()),
924            Value::BigDecimal(v) => Ok(v.to_string()),
925            Value::Empty(_) => Err(ValueError::NoValue),
926        }
927    }
928
929    // ========================================================================
930    // Type-setting setters (strict type matching)
931    // ========================================================================
932
933    impl_set_value! {
934        /// Set boolean value
935        ///
936        /// # Parameters
937        ///
938        /// * `value` - The boolean value to set
939        ///
940        /// # Returns
941        ///
942        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
943        ///
944        /// # Example
945        ///
946        /// ```rust,ignore
947        /// use crate::util::value::Value;
948        ///
949        /// let mut value = Value::Empty(DataType::Bool);
950        /// value.set_bool(true).unwrap();
951        /// assert_eq!(value.get_bool().unwrap(), true);
952        /// ```
953        copy: set_bool, Bool, bool, DataType::Bool
954    }
955
956    impl_set_value! {
957        /// Set character value
958        ///
959        /// # Parameters
960        ///
961        /// * `value` - The character value to set
962        ///
963        /// # Returns
964        ///
965        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
966        copy: set_char, Char, char, DataType::Char
967    }
968
969    impl_set_value! {
970        /// Set int8 value
971        ///
972        /// # Parameters
973        ///
974        /// * `value` - The int8 value to set
975        ///
976        /// # Returns
977        ///
978        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
979        copy: set_int8, Int8, i8, DataType::Int8
980    }
981
982    impl_set_value! {
983        /// Set int16 value
984        ///
985        /// # Parameters
986        ///
987        /// * `value` - The int16 value to set
988        ///
989        /// # Returns
990        ///
991        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
992        copy: set_int16, Int16, i16, DataType::Int16
993    }
994
995    impl_set_value! {
996        /// Set int32 value
997        ///
998        /// # Parameters
999        ///
1000        /// * `value` - The int32 value to set
1001        ///
1002        /// # Returns
1003        ///
1004        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1005        copy: set_int32, Int32, i32, DataType::Int32
1006    }
1007
1008    impl_set_value! {
1009        /// Set int64 value
1010        ///
1011        /// # Parameters
1012        ///
1013        /// * `value` - The int64 value to set
1014        ///
1015        /// # Returns
1016        ///
1017        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1018        copy: set_int64, Int64, i64, DataType::Int64
1019    }
1020
1021    impl_set_value! {
1022        /// Set int128 value
1023        ///
1024        /// # Parameters
1025        ///
1026        /// * `value` - The int128 value to set
1027        ///
1028        /// # Returns
1029        ///
1030        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1031        copy: set_int128, Int128, i128, DataType::Int128
1032    }
1033
1034    impl_set_value! {
1035        /// Set uint8 value
1036        ///
1037        /// # Parameters
1038        ///
1039        /// * `value` - The uint8 value to set
1040        ///
1041        /// # Returns
1042        ///
1043        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1044        copy: set_uint8, UInt8, u8, DataType::UInt8
1045    }
1046
1047    impl_set_value! {
1048        /// Set uint16 value
1049        ///
1050        /// # Parameters
1051        ///
1052        /// * `value` - The uint16 value to set
1053        ///
1054        /// # Returns
1055        ///
1056        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1057        copy: set_uint16, UInt16, u16, DataType::UInt16
1058    }
1059
1060    impl_set_value! {
1061        /// Set uint32 value
1062        ///
1063        /// # Parameters
1064        ///
1065        /// * `value` - The uint32 value to set
1066        ///
1067        /// # Returns
1068        ///
1069        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1070        copy: set_uint32, UInt32, u32, DataType::UInt32
1071    }
1072
1073    impl_set_value! {
1074        /// Set uint64 value
1075        ///
1076        /// # Parameters
1077        ///
1078        /// * `value` - The uint64 value to set
1079        ///
1080        /// # Returns
1081        ///
1082        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1083        copy: set_uint64, UInt64, u64, DataType::UInt64
1084    }
1085
1086    impl_set_value! {
1087        /// Set uint128 value
1088        ///
1089        /// # Parameters
1090        ///
1091        /// * `value` - The uint128 value to set
1092        ///
1093        /// # Returns
1094        ///
1095        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1096        copy: set_uint128, UInt128, u128, DataType::UInt128
1097    }
1098
1099    impl_set_value! {
1100        /// Set float32 value
1101        ///
1102        /// # Parameters
1103        ///
1104        /// * `value` - The float32 value to set
1105        ///
1106        /// # Returns
1107        ///
1108        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1109        copy: set_float32, Float32, f32, DataType::Float32
1110    }
1111
1112    impl_set_value! {
1113        /// Set float64 value
1114        ///
1115        /// # Parameters
1116        ///
1117        /// * `value` - The float64 value to set
1118        ///
1119        /// # Returns
1120        ///
1121        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1122        copy: set_float64, Float64, f64, DataType::Float64
1123    }
1124
1125    impl_set_value! {
1126        /// Set string value
1127        ///
1128        /// # Parameters
1129        ///
1130        /// * `value` - The string value to set
1131        ///
1132        /// # Returns
1133        ///
1134        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1135        ///
1136        /// # Example
1137        ///
1138        /// ```rust,ignore
1139        /// use crate::util::value::Value;
1140        ///
1141        /// let mut value = Value::Empty(DataType::String);
1142        /// value.set_string("hello".to_string()).unwrap();
1143        /// assert_eq!(value.get_string().unwrap(), "hello");
1144        /// ```
1145        owned: set_string, String, String, DataType::String
1146    }
1147
1148    impl_set_value! {
1149        /// Set date value
1150        ///
1151        /// # Parameters
1152        ///
1153        /// * `value` - The date value to set
1154        ///
1155        /// # Returns
1156        ///
1157        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1158        copy: set_date, Date, NaiveDate, DataType::Date
1159    }
1160
1161    impl_set_value! {
1162        /// Set time value
1163        ///
1164        /// # Parameters
1165        ///
1166        /// * `value` - The time value to set
1167        ///
1168        /// # Returns
1169        ///
1170        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1171        copy: set_time, Time, NaiveTime, DataType::Time
1172    }
1173
1174    impl_set_value! {
1175        /// Set datetime value
1176        ///
1177        /// # Parameters
1178        ///
1179        /// * `value` - The datetime value to set
1180        ///
1181        /// # Returns
1182        ///
1183        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1184        copy: set_datetime, DateTime, NaiveDateTime, DataType::DateTime
1185    }
1186
1187    impl_set_value! {
1188        /// Set UTC instant value
1189        ///
1190        /// # Parameters
1191        ///
1192        /// * `value` - The UTC instant value to set
1193        ///
1194        /// # Returns
1195        ///
1196        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1197        copy: set_instant, Instant, DateTime<Utc>, DataType::Instant
1198    }
1199
1200    impl_set_value! {
1201        /// Set big integer value
1202        ///
1203        /// # Parameters
1204        ///
1205        /// * `value` - The big integer value to set
1206        ///
1207        /// # Returns
1208        ///
1209        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1210        ///
1211        /// # Example
1212        ///
1213        /// ```rust,ignore
1214        /// use crate::util::value::Value;
1215        /// use num_bigint::BigInt;
1216        ///
1217        /// let mut value = Value::Empty(DataType::BigInteger);
1218        /// value.set_biginteger(BigInt::from(123456789)).unwrap();
1219        /// assert_eq!(value.get_biginteger().unwrap(), BigInt::from(123456789));
1220        /// ```
1221        owned: set_biginteger, BigInteger, BigInt, DataType::BigInteger
1222    }
1223
1224    impl_set_value! {
1225        /// Set big decimal value
1226        ///
1227        /// # Parameters
1228        ///
1229        /// * `value` - The big decimal value to set
1230        ///
1231        /// # Returns
1232        ///
1233        /// If setting succeeds, returns `Ok(())`; otherwise returns an error
1234        ///
1235        /// # Example
1236        ///
1237        /// ```rust,ignore
1238        /// use crate::util::value::Value;
1239        /// use bigdecimal::BigDecimal;
1240        ///
1241        /// let mut value = Value::Empty(DataType::BigDecimal);
1242        /// value.set_bigdecimal(BigDecimal::from(123.456)).unwrap();
1243        /// assert_eq!(value.get_bigdecimal().unwrap(), BigDecimal::from(123.456));
1244        /// ```
1245        owned: set_bigdecimal, BigDecimal, BigDecimal, DataType::BigDecimal
1246    }
1247}
1248
1249impl Default for Value {
1250    fn default() -> Self {
1251        Value::Empty(DataType::String)
1252    }
1253}
1254
1255// ============================================================================
1256// Internal generic conversion traits (private, not exported, to avoid polluting the standard type namespace)
1257// ============================================================================
1258
1259/// Internal trait: used to extract specific types from Value
1260///
1261/// This trait is not exported in mod.rs, only used for internal implementation, to avoid polluting the standard type namespace
1262#[doc(hidden)]
1263pub trait ValueGetter<T> {
1264    fn get_value(&self) -> ValueResult<T>;
1265}
1266
1267/// Internal trait: used to create Value from types
1268///
1269/// This trait is not exported in mod.rs, only used for internal implementation, to avoid polluting the standard type namespace
1270#[doc(hidden)]
1271pub trait ValueConstructor<T> {
1272    fn from_type(value: T) -> Self;
1273}
1274
1275/// Internal trait: used to set specific types in Value
1276///
1277/// This trait is not exported in mod.rs, only used for internal implementation, to avoid polluting the standard type namespace
1278#[doc(hidden)]
1279pub trait ValueSetter<T> {
1280    fn set_value(&mut self, value: T) -> ValueResult<()>;
1281}
1282
1283// ============================================================================
1284// Implementation of internal traits (simplified using macros)
1285// ============================================================================
1286
1287macro_rules! impl_value_traits {
1288    ($type:ty, $variant:ident, $get_method:ident, $set_method:ident) => {
1289        impl ValueGetter<$type> for Value {
1290            fn get_value(&self) -> ValueResult<$type> {
1291                self.$get_method()
1292            }
1293        }
1294
1295        impl ValueSetter<$type> for Value {
1296            fn set_value(&mut self, value: $type) -> ValueResult<()> {
1297                self.$set_method(value)
1298            }
1299        }
1300
1301        impl ValueConstructor<$type> for Value {
1302            fn from_type(value: $type) -> Self {
1303                Value::$variant(value)
1304            }
1305        }
1306    };
1307}
1308
1309// Implementation for Copy types
1310impl_value_traits!(bool, Bool, get_bool, set_bool);
1311impl_value_traits!(char, Char, get_char, set_char);
1312impl_value_traits!(i8, Int8, get_int8, set_int8);
1313impl_value_traits!(i16, Int16, get_int16, set_int16);
1314impl_value_traits!(i32, Int32, get_int32, set_int32);
1315impl_value_traits!(i64, Int64, get_int64, set_int64);
1316impl_value_traits!(i128, Int128, get_int128, set_int128);
1317impl_value_traits!(u8, UInt8, get_uint8, set_uint8);
1318impl_value_traits!(u16, UInt16, get_uint16, set_uint16);
1319impl_value_traits!(u32, UInt32, get_uint32, set_uint32);
1320impl_value_traits!(u64, UInt64, get_uint64, set_uint64);
1321impl_value_traits!(u128, UInt128, get_uint128, set_uint128);
1322impl_value_traits!(f32, Float32, get_float32, set_float32);
1323impl_value_traits!(f64, Float64, get_float64, set_float64);
1324impl_value_traits!(NaiveDate, Date, get_date, set_date);
1325impl_value_traits!(NaiveTime, Time, get_time, set_time);
1326impl_value_traits!(NaiveDateTime, DateTime, get_datetime, set_datetime);
1327impl_value_traits!(DateTime<Utc>, Instant, get_instant, set_instant);
1328impl_value_traits!(BigInt, BigInteger, get_biginteger, set_biginteger);
1329impl_value_traits!(BigDecimal, BigDecimal, get_bigdecimal, set_bigdecimal);
1330
1331// String needs cloning
1332impl ValueGetter<String> for Value {
1333    fn get_value(&self) -> ValueResult<String> {
1334        self.get_string().map(|s| s.to_string())
1335    }
1336}
1337
1338impl ValueSetter<String> for Value {
1339    fn set_value(&mut self, value: String) -> ValueResult<()> {
1340        self.set_string(value)
1341    }
1342}
1343
1344impl ValueConstructor<String> for Value {
1345    fn from_type(value: String) -> Self {
1346        Value::String(value)
1347    }
1348}
1349
1350// Special handling for &str - convert to String
1351impl ValueSetter<&str> for Value {
1352    fn set_value(&mut self, value: &str) -> ValueResult<()> {
1353        self.set_string(value.to_string())
1354    }
1355}
1356
1357impl ValueConstructor<&str> for Value {
1358    fn from_type(value: &str) -> Self {
1359        Value::String(value.to_string())
1360    }
1361}