qubit_value/value/value_accessors.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10
11use std::collections::HashMap;
12use std::time::Duration;
13
14use bigdecimal::BigDecimal;
15use chrono::{
16 DateTime,
17 NaiveDate,
18 NaiveDateTime,
19 NaiveTime,
20 Utc,
21};
22use num_bigint::BigInt;
23use serde::Serialize;
24use serde::de::DeserializeOwned;
25use url::Url;
26
27use qubit_datatype::DataType;
28
29use super::value::Value;
30use crate::value_error::{
31 ValueError,
32 ValueResult,
33};
34
35macro_rules! impl_get_value {
36 // Copy type: directly dereference and return
37 ($(#[$attr:meta])* copy: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
38 $(#[$attr])*
39 #[inline]
40 pub fn $method(&self) -> ValueResult<$type> {
41 match self {
42 Value::$variant(v) => Ok(*v),
43 Value::Empty(dt) if *dt == $data_type => Err(ValueError::NoValue),
44 Value::Empty(dt) => Err(ValueError::TypeMismatch {
45 expected: $data_type,
46 actual: *dt,
47 }),
48 _ => Err(ValueError::TypeMismatch {
49 expected: $data_type,
50 actual: self.data_type(),
51 }),
52 }
53 }
54 };
55
56 // Reference type: use conversion function to return reference,
57 // fixing lifetime issues
58 ($(#[$attr:meta])* ref: $method:ident, $variant:ident, $ret_type:ty, $data_type:expr, $conversion:expr) => {
59 $(#[$attr])*
60 #[inline]
61 pub fn $method(&self) -> ValueResult<$ret_type> {
62 match self {
63 Value::$variant(v) => {
64 let conv_fn: fn(&_) -> $ret_type = $conversion;
65 Ok(conv_fn(v))
66 },
67 Value::Empty(dt) if *dt == $data_type => Err(ValueError::NoValue),
68 Value::Empty(dt) => Err(ValueError::TypeMismatch {
69 expected: $data_type,
70 actual: *dt,
71 }),
72 _ => Err(ValueError::TypeMismatch {
73 expected: $data_type,
74 actual: self.data_type(),
75 }),
76 }
77 }
78 };
79}
80
81/// Unified setter generation macro
82///
83/// Supports two modes:
84/// 1. `copy:` - For types implementing the Copy trait, directly sets the value
85/// 2. `owned:` - For non-Copy types, requires owning the value
86///
87/// # Documentation Comment Support
88///
89/// The macro automatically extracts preceding documentation comments, so
90/// you can add `///` comments before macro invocations.
91///
92///
93macro_rules! impl_set_value {
94 // Copy type: directly set the value
95 ($(#[$attr:meta])* copy: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
96 $(#[$attr])*
97 #[inline]
98 pub fn $method(&mut self, value: $type) -> ValueResult<()> {
99 *self = Value::$variant(value);
100 Ok(())
101 }
102 };
103
104 // Owned type: set the owned value
105 ($(#[$attr:meta])* owned: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
106 $(#[$attr])*
107 #[inline]
108 pub fn $method(&mut self, value: $type) -> ValueResult<()> {
109 *self = Value::$variant(value);
110 Ok(())
111 }
112 };
113}
114
115impl Value {
116 // ========================================================================
117 // Type-checking getters (strict type matching)
118 // ========================================================================
119
120 impl_get_value! {
121 /// Get boolean value
122 ///
123 /// # Returns
124 ///
125 /// If types match, returns the boolean value; otherwise returns an
126 /// error.
127 ///
128 /// # Example
129 ///
130 /// ```rust
131 /// use qubit_value::Value;
132 ///
133 /// let value = Value::Bool(true);
134 /// assert_eq!(value.get_bool().unwrap(), true);
135 /// ```
136 copy: get_bool, Bool, bool, DataType::Bool
137 }
138
139 impl_get_value! {
140 /// Get character value
141 ///
142 /// # Returns
143 ///
144 /// If types match, returns the character value; otherwise returns an
145 /// error.
146 ///
147 /// # Example
148 ///
149 /// ```rust
150 /// use qubit_value::Value;
151 ///
152 /// let value = Value::Char('A');
153 /// assert_eq!(value.get_char().unwrap(), 'A');
154 /// ```
155 copy: get_char, Char, char, DataType::Char
156 }
157
158 impl_get_value! {
159 /// Get int8 value
160 ///
161 /// # Returns
162 ///
163 /// If types match, returns the int8 value; otherwise returns an error.
164 copy: get_int8, Int8, i8, DataType::Int8
165 }
166
167 impl_get_value! {
168 /// Get int16 value
169 ///
170 /// # Returns
171 ///
172 /// If types match, returns the int16 value; otherwise returns an error
173 copy: get_int16, Int16, i16, DataType::Int16
174 }
175
176 impl_get_value! {
177 /// Get int32 value
178 ///
179 /// # Returns
180 ///
181 /// If types match, returns the int32 value; otherwise returns an error.
182 copy: get_int32, Int32, i32, DataType::Int32
183 }
184
185 impl_get_value! {
186 /// Get int64 value
187 ///
188 /// # Returns
189 ///
190 /// If types match, returns the int64 value; otherwise returns an error
191 copy: get_int64, Int64, i64, DataType::Int64
192 }
193
194 impl_get_value! {
195 /// Get int128 value
196 ///
197 /// # Returns
198 ///
199 /// If types match, returns the int128 value; otherwise returns an error.
200 copy: get_int128, Int128, i128, DataType::Int128
201 }
202
203 impl_get_value! {
204 /// Get uint8 value
205 ///
206 /// # Returns
207 ///
208 /// If types match, returns the uint8 value; otherwise returns an error
209 copy: get_uint8, UInt8, u8, DataType::UInt8
210 }
211
212 impl_get_value! {
213 /// Get uint16 value
214 ///
215 /// # Returns
216 ///
217 /// If types match, returns the uint16 value; otherwise returns an error.
218 copy: get_uint16, UInt16, u16, DataType::UInt16
219 }
220
221 impl_get_value! {
222 /// Get uint32 value
223 ///
224 /// # Returns
225 ///
226 /// If types match, returns the uint32 value; otherwise returns an error.
227 copy: get_uint32, UInt32, u32, DataType::UInt32
228 }
229
230 impl_get_value! {
231 /// Get uint64 value
232 ///
233 /// # Returns
234 ///
235 /// If types match, returns the uint64 value; otherwise returns an error.
236 copy: get_uint64, UInt64, u64, DataType::UInt64
237 }
238
239 impl_get_value! {
240 /// Get uint128 value
241 ///
242 /// # Returns
243 ///
244 /// If types match, returns the uint128 value; otherwise returns an error
245 copy: get_uint128, UInt128, u128, DataType::UInt128
246 }
247
248 impl_get_value! {
249 /// Get float32 value
250 ///
251 /// # Returns
252 ///
253 /// If types match, returns the float32 value; otherwise returns an error.
254 copy: get_float32, Float32, f32, DataType::Float32
255 }
256
257 impl_get_value! {
258 /// Get float64 value
259 ///
260 /// # Returns
261 ///
262 /// If types match, returns the float64 value; otherwise returns an error
263 copy: get_float64, Float64, f64, DataType::Float64
264 }
265
266 impl_get_value! {
267 /// Get string reference
268 ///
269 /// # Returns
270 ///
271 /// If types match, returns a reference to the string; otherwise returns
272 /// an error.
273 ///
274 /// # Example
275 ///
276 /// ```rust
277 /// use qubit_value::Value;
278 ///
279 /// let value = Value::String("hello".to_string());
280 /// assert_eq!(value.get_string().unwrap(), "hello");
281 /// ```
282 ref: get_string, String, &str, DataType::String, |s: &String| s.as_str()
283 }
284
285 impl_get_value! {
286 /// Get date value
287 ///
288 /// # Returns
289 ///
290 /// If types match, returns the date value; otherwise returns an error.
291 copy: get_date, Date, NaiveDate, DataType::Date
292 }
293
294 impl_get_value! {
295 /// Get time value
296 ///
297 /// # Returns
298 ///
299 /// If types match, returns the time value; otherwise returns an error.
300 copy: get_time, Time, NaiveTime, DataType::Time
301 }
302
303 impl_get_value! {
304 /// Get datetime value
305 ///
306 /// # Returns
307 ///
308 /// If types match, returns the datetime value; otherwise returns an error.
309 copy: get_datetime, DateTime, NaiveDateTime, DataType::DateTime
310 }
311
312 impl_get_value! {
313 /// Get UTC instant value
314 ///
315 /// # Returns
316 ///
317 /// If types match, returns the UTC instant value; otherwise returns an error.
318 copy: get_instant, Instant, DateTime<Utc>, DataType::Instant
319 }
320
321 impl_get_value! {
322 /// Get big integer value.
323 ///
324 /// This method returns a cloned [`BigInt`]. Use
325 /// [`Value::get_biginteger_ref`] to borrow the stored value without
326 /// cloning.
327 ///
328 /// # Returns
329 ///
330 /// If types match, returns the big integer value; otherwise returns an error.
331 ///
332 /// # Example
333 ///
334 /// ```rust
335 /// use qubit_value::Value;
336 /// use num_bigint::BigInt;
337 ///
338 /// let value = Value::BigInteger(BigInt::from(123456789));
339 /// assert_eq!(value.get_biginteger().unwrap(), BigInt::from(123456789));
340 /// ```
341 ref: get_biginteger, BigInteger, BigInt, DataType::BigInteger, |v: &BigInt| v.clone()
342 }
343
344 impl_get_value! {
345 /// Get big decimal value.
346 ///
347 /// This method returns a cloned [`BigDecimal`]. Use
348 /// [`Value::get_bigdecimal_ref`] to borrow the stored value without
349 /// cloning.
350 ///
351 /// # Returns
352 ///
353 /// If types match, returns the big decimal value; otherwise returns an
354 /// error.
355 ///
356 /// # Example
357 ///
358 /// ```rust
359 /// use std::str::FromStr;
360 ///
361 /// use bigdecimal::BigDecimal;
362 /// use qubit_value::Value;
363 ///
364 /// let bd = BigDecimal::from_str("123.456").unwrap();
365 /// let value = Value::BigDecimal(bd.clone());
366 /// assert_eq!(value.get_bigdecimal().unwrap(), bd);
367 /// ```
368 ref: get_bigdecimal, BigDecimal, BigDecimal, DataType::BigDecimal, |v: &BigDecimal| v.clone()
369 }
370
371 // ========================================================================
372 // Type-setting setters (strict type matching)
373 // ========================================================================
374
375 impl_set_value! {
376 /// Set boolean value
377 ///
378 /// # Parameters
379 ///
380 /// * `value` - The boolean value to set
381 ///
382 /// # Returns
383 ///
384 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
385 ///
386 /// # Example
387 ///
388 /// ```rust
389 /// use qubit_datatype::DataType;
390 /// use qubit_value::Value;
391 ///
392 /// let mut value = Value::Empty(DataType::Bool);
393 /// value.set_bool(true).unwrap();
394 /// assert_eq!(value.get_bool().unwrap(), true);
395 /// ```
396 copy: set_bool, Bool, bool, DataType::Bool
397 }
398
399 impl_set_value! {
400 /// Set character value
401 ///
402 /// # Parameters
403 ///
404 /// * `value` - The character value to set
405 ///
406 /// # Returns
407 ///
408 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
409 copy: set_char, Char, char, DataType::Char
410 }
411
412 impl_set_value! {
413 /// Set int8 value
414 ///
415 /// # Parameters
416 ///
417 /// * `value` - The int8 value to set
418 ///
419 /// # Returns
420 ///
421 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
422 copy: set_int8, Int8, i8, DataType::Int8
423 }
424
425 impl_set_value! {
426 /// Set int16 value
427 ///
428 /// # Parameters
429 ///
430 /// * `value` - The int16 value to set
431 ///
432 /// # Returns
433 ///
434 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
435 copy: set_int16, Int16, i16, DataType::Int16
436 }
437
438 impl_set_value! {
439 /// Set int32 value
440 ///
441 /// # Parameters
442 ///
443 /// * `value` - The int32 value to set
444 ///
445 /// # Returns
446 ///
447 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
448 copy: set_int32, Int32, i32, DataType::Int32
449 }
450
451 impl_set_value! {
452 /// Set int64 value
453 ///
454 /// # Parameters
455 ///
456 /// * `value` - The int64 value to set
457 ///
458 /// # Returns
459 ///
460 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
461 copy: set_int64, Int64, i64, DataType::Int64
462 }
463
464 impl_set_value! {
465 /// Set int128 value
466 ///
467 /// # Parameters
468 ///
469 /// * `value` - The int128 value to set
470 ///
471 /// # Returns
472 ///
473 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
474 copy: set_int128, Int128, i128, DataType::Int128
475 }
476
477 impl_set_value! {
478 /// Set uint8 value
479 ///
480 /// # Parameters
481 ///
482 /// * `value` - The uint8 value to set
483 ///
484 /// # Returns
485 ///
486 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
487 copy: set_uint8, UInt8, u8, DataType::UInt8
488 }
489
490 impl_set_value! {
491 /// Set uint16 value
492 ///
493 /// # Parameters
494 ///
495 /// * `value` - The uint16 value to set
496 ///
497 /// # Returns
498 ///
499 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
500 copy: set_uint16, UInt16, u16, DataType::UInt16
501 }
502
503 impl_set_value! {
504 /// Set uint32 value
505 ///
506 /// # Parameters
507 ///
508 /// * `value` - The uint32 value to set
509 ///
510 /// # Returns
511 ///
512 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
513 copy: set_uint32, UInt32, u32, DataType::UInt32
514 }
515
516 impl_set_value! {
517 /// Set uint64 value
518 ///
519 /// # Parameters
520 ///
521 /// * `value` - The uint64 value to set
522 ///
523 /// # Returns
524 ///
525 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
526 copy: set_uint64, UInt64, u64, DataType::UInt64
527 }
528
529 impl_set_value! {
530 /// Set uint128 value
531 ///
532 /// # Parameters
533 ///
534 /// * `value` - The uint128 value to set
535 ///
536 /// # Returns
537 ///
538 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
539 copy: set_uint128, UInt128, u128, DataType::UInt128
540 }
541
542 impl_set_value! {
543 /// Set float32 value
544 ///
545 /// # Parameters
546 ///
547 /// * `value` - The float32 value to set
548 ///
549 /// # Returns
550 ///
551 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
552 copy: set_float32, Float32, f32, DataType::Float32
553 }
554
555 impl_set_value! {
556 /// Set float64 value
557 ///
558 /// # Parameters
559 ///
560 /// * `value` - The float64 value to set
561 ///
562 /// # Returns
563 ///
564 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
565 copy: set_float64, Float64, f64, DataType::Float64
566 }
567
568 impl_set_value! {
569 /// Set string value
570 ///
571 /// # Parameters
572 ///
573 /// * `value` - The string value to set
574 ///
575 /// # Returns
576 ///
577 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
578 ///
579 /// # Example
580 ///
581 /// ```rust
582 /// use qubit_datatype::DataType;
583 /// use qubit_value::Value;
584 ///
585 /// let mut value = Value::Empty(DataType::String);
586 /// value.set_string("hello".to_string()).unwrap();
587 /// assert_eq!(value.get_string().unwrap(), "hello");
588 /// ```
589 owned: set_string, String, String, DataType::String
590 }
591
592 impl_set_value! {
593 /// Set date value
594 ///
595 /// # Parameters
596 ///
597 /// * `value` - The date value to set
598 ///
599 /// # Returns
600 ///
601 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
602 copy: set_date, Date, NaiveDate, DataType::Date
603 }
604
605 impl_set_value! {
606 /// Set time value
607 ///
608 /// # Parameters
609 ///
610 /// * `value` - The time value to set
611 ///
612 /// # Returns
613 ///
614 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
615 copy: set_time, Time, NaiveTime, DataType::Time
616 }
617
618 impl_set_value! {
619 /// Set datetime value
620 ///
621 /// # Parameters
622 ///
623 /// * `value` - The datetime value to set
624 ///
625 /// # Returns
626 ///
627 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
628 copy: set_datetime, DateTime, NaiveDateTime, DataType::DateTime
629 }
630
631 impl_set_value! {
632 /// Set UTC instant value
633 ///
634 /// # Parameters
635 ///
636 /// * `value` - The UTC instant value to set
637 ///
638 /// # Returns
639 ///
640 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
641 copy: set_instant, Instant, DateTime<Utc>, DataType::Instant
642 }
643
644 impl_set_value! {
645 /// Set big integer value
646 ///
647 /// # Parameters
648 ///
649 /// * `value` - The big integer value to set
650 ///
651 /// # Returns
652 ///
653 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
654 ///
655 /// # Example
656 ///
657 /// ```rust
658 /// use num_bigint::BigInt;
659 /// use qubit_datatype::DataType;
660 /// use qubit_value::Value;
661 ///
662 /// let mut value = Value::Empty(DataType::BigInteger);
663 /// value.set_biginteger(BigInt::from(123456789)).unwrap();
664 /// assert_eq!(value.get_biginteger().unwrap(), BigInt::from(123456789));
665 /// ```
666 owned: set_biginteger, BigInteger, BigInt, DataType::BigInteger
667 }
668
669 impl_set_value! {
670 /// Set big decimal value
671 ///
672 /// # Parameters
673 ///
674 /// * `value` - The big decimal value to set
675 ///
676 /// # Returns
677 ///
678 /// If setting succeeds, returns `Ok(())`; otherwise returns an error.
679 ///
680 /// # Example
681 ///
682 /// ```rust
683 /// use std::str::FromStr;
684 ///
685 /// use bigdecimal::BigDecimal;
686 /// use qubit_datatype::DataType;
687 /// use qubit_value::Value;
688 ///
689 /// let mut value = Value::Empty(DataType::BigDecimal);
690 /// let bd = BigDecimal::from_str("123.456").unwrap();
691 /// value.set_bigdecimal(bd.clone()).unwrap();
692 /// assert_eq!(value.get_bigdecimal().unwrap(), bd);
693 /// ```
694 owned: set_bigdecimal, BigDecimal, BigDecimal, DataType::BigDecimal
695 }
696
697 impl_get_value! {
698 /// Get isize value
699 ///
700 /// # Returns
701 ///
702 /// If types match, returns the isize value; otherwise returns an error.
703 copy: get_intsize, IntSize, isize, DataType::IntSize
704 }
705
706 impl_get_value! {
707 /// Get usize value
708 ///
709 /// # Returns
710 ///
711 /// If types match, returns the usize value; otherwise returns an error.
712 copy: get_uintsize, UIntSize, usize, DataType::UIntSize
713 }
714
715 impl_get_value! {
716 /// Get Duration value
717 ///
718 /// # Returns
719 ///
720 /// If types match, returns the Duration value; otherwise returns an
721 /// error.
722 copy: get_duration, Duration, Duration, DataType::Duration
723 }
724
725 impl_get_value! {
726 /// Get URL value.
727 ///
728 /// This method returns a cloned [`Url`]. Use [`Value::get_url_ref`] to
729 /// borrow the stored value without cloning.
730 ///
731 /// # Returns
732 ///
733 /// If types match, returns the URL value; otherwise returns an error.
734 ref: get_url, Url, Url, DataType::Url, |v: &Url| v.clone()
735 }
736
737 impl_get_value! {
738 /// Get string map value.
739 ///
740 /// This method returns a cloned `HashMap<String, String>`. Use
741 /// [`Value::get_string_map_ref`] to borrow the stored value without
742 /// cloning.
743 ///
744 /// # Returns
745 ///
746 /// If types match, returns the string map value; otherwise returns an
747 /// error.
748 ref: get_string_map, StringMap, HashMap<String, String>, DataType::StringMap,
749 |v: &HashMap<String, String>| v.clone()
750 }
751
752 impl_get_value! {
753 /// Get JSON value.
754 ///
755 /// This method returns a cloned [`serde_json::Value`]. Use
756 /// [`Value::get_json_ref`] to borrow the stored value without cloning.
757 ///
758 /// # Returns
759 ///
760 /// If types match, returns the JSON value; otherwise returns an error.
761 ref: get_json, Json, serde_json::Value, DataType::Json,
762 |v: &serde_json::Value| v.clone()
763 }
764
765 /// Borrow the inner `BigInt` without cloning.
766 pub fn get_biginteger_ref(&self) -> ValueResult<&BigInt> {
767 match self {
768 Value::BigInteger(v) => Ok(v),
769 Value::Empty(_) => Err(ValueError::NoValue),
770 _ => Err(ValueError::TypeMismatch {
771 expected: DataType::BigInteger,
772 actual: self.data_type(),
773 }),
774 }
775 }
776
777 /// Borrow the inner `BigDecimal` without cloning.
778 pub fn get_bigdecimal_ref(&self) -> ValueResult<&BigDecimal> {
779 match self {
780 Value::BigDecimal(v) => Ok(v),
781 Value::Empty(_) => Err(ValueError::NoValue),
782 _ => Err(ValueError::TypeMismatch {
783 expected: DataType::BigDecimal,
784 actual: self.data_type(),
785 }),
786 }
787 }
788
789 /// Borrow the inner `Url` without cloning.
790 pub fn get_url_ref(&self) -> ValueResult<&Url> {
791 match self {
792 Value::Url(v) => Ok(v),
793 Value::Empty(_) => Err(ValueError::NoValue),
794 _ => Err(ValueError::TypeMismatch {
795 expected: DataType::Url,
796 actual: self.data_type(),
797 }),
798 }
799 }
800
801 /// Borrow the inner `HashMap<String, String>` without cloning.
802 pub fn get_string_map_ref(&self) -> ValueResult<&HashMap<String, String>> {
803 match self {
804 Value::StringMap(v) => Ok(v),
805 Value::Empty(_) => Err(ValueError::NoValue),
806 _ => Err(ValueError::TypeMismatch {
807 expected: DataType::StringMap,
808 actual: self.data_type(),
809 }),
810 }
811 }
812
813 /// Borrow the inner JSON value without cloning.
814 pub fn get_json_ref(&self) -> ValueResult<&serde_json::Value> {
815 match self {
816 Value::Json(v) => Ok(v),
817 Value::Empty(_) => Err(ValueError::NoValue),
818 _ => Err(ValueError::TypeMismatch {
819 expected: DataType::Json,
820 actual: self.data_type(),
821 }),
822 }
823 }
824
825 impl_set_value! {
826 /// Set isize value
827 copy: set_intsize, IntSize, isize, DataType::IntSize
828 }
829
830 impl_set_value! {
831 /// Set usize value
832 copy: set_uintsize, UIntSize, usize, DataType::UIntSize
833 }
834
835 impl_set_value! {
836 /// Set Duration value
837 copy: set_duration, Duration, Duration, DataType::Duration
838 }
839
840 impl_set_value! {
841 /// Set Url value
842 owned: set_url, Url, Url, DataType::Url
843 }
844
845 impl_set_value! {
846 /// Set StringMap value
847 owned: set_string_map, StringMap, HashMap<String, String>, DataType::StringMap
848 }
849
850 impl_set_value! {
851 /// Set Json value
852 owned: set_json, Json, serde_json::Value, DataType::Json
853 }
854
855 /// Create a `Value` from a `serde_json::Value`.
856 ///
857 /// # Parameters
858 ///
859 /// * `json` - The JSON value to wrap.
860 ///
861 /// # Returns
862 ///
863 /// Returns a `Value::Json` wrapping the given JSON value.
864 #[inline]
865 pub fn from_json_value(json: serde_json::Value) -> Self {
866 Value::Json(json)
867 }
868
869 /// Create a `Value` from any serializable value by converting it to JSON.
870 ///
871 /// # Type Parameters
872 ///
873 /// * `T` - Any type implementing `Serialize`.
874 ///
875 /// # Parameters
876 ///
877 /// * `value` - The value to serialize into JSON.
878 ///
879 /// # Returns
880 ///
881 /// Returns `Ok(Value::Json(...))` on success, or an error if
882 /// serialization fails.
883 pub fn from_serializable<T: Serialize>(value: &T) -> ValueResult<Self> {
884 let json = serde_json::to_value(value)
885 .map_err(|e| ValueError::JsonSerializationError(e.to_string()))?;
886 Ok(Value::Json(json))
887 }
888
889 /// Deserialize the inner JSON value into a target type.
890 ///
891 /// Only works when `self` is `Value::Json(...)`.
892 ///
893 /// # Type Parameters
894 ///
895 /// * `T` - The target type implementing `DeserializeOwned`.
896 ///
897 /// # Returns
898 ///
899 /// Returns `Ok(T)` on success, or an error if the value is not JSON
900 /// or deserialization fails.
901 pub fn deserialize_json<T: DeserializeOwned>(&self) -> ValueResult<T> {
902 match self {
903 Value::Json(v) => serde_json::from_value(v.clone())
904 .map_err(|e| ValueError::JsonDeserializationError(e.to_string())),
905 Value::Empty(_) => Err(ValueError::NoValue),
906 _ => Err(ValueError::ConversionFailed {
907 from: self.data_type(),
908 to: DataType::Json,
909 }),
910 }
911 }
912}