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