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