sonic_rs/value/
tryfrom.rs

1use super::Value;
2use crate::{LazyValue, Number};
3
4impl TryFrom<f32> for Value {
5    type Error = crate::Error;
6
7    /// Try convert a f32 to `Value`. If the float is NaN or infinity, return a error.
8    ///
9    /// # Examples
10    ///
11    /// ```
12    /// use sonic_rs::{JsonValueTrait, Value};
13    ///
14    /// let f1: f32 = 2.333;
15    /// let x1: Value = f1.try_into().unwrap();
16    /// assert_eq!(x1, f1);
17    ///
18    /// let x2: Value = f32::INFINITY.try_into().unwrap_or_default();
19    /// let x3: Value = f32::NAN.try_into().unwrap_or_default();
20    ///
21    /// assert!(x2.is_null() && x3.is_null());
22    /// ```
23    #[inline]
24    fn try_from(value: f32) -> Result<Self, Self::Error> {
25        Number::try_from(value).map(Into::into)
26    }
27}
28
29impl TryFrom<f64> for Value {
30    /// Try convert a f64 to `Value`. If the float is NaN or infinity, return a error.
31    ///
32    /// # Examples
33    ///
34    /// ```
35    /// use sonic_rs::{JsonValueTrait, Value};
36    ///
37    /// let f1: f64 = 2.333;
38    /// let x1: Value = f1.try_into().unwrap();
39    /// assert_eq!(x1, 2.333);
40    ///
41    /// let x2: Value = f64::INFINITY.try_into().unwrap_or_default();
42    /// let x3: Value = f64::NAN.try_into().unwrap_or_default();
43    ///
44    /// assert!(x2.is_null() && x3.is_null());
45    /// ```
46    type Error = crate::Error;
47    #[inline]
48    fn try_from(value: f64) -> Result<Self, Self::Error> {
49        Number::try_from(value).map(Into::into)
50    }
51}
52
53/// Try parse a `LazyValue` into a `Value`.  `LazyValue` is always a valid JSON, at least it is
54/// followed the JSON syntax.
55///
56/// However, in some cases, the parse will failed and return errors, such as the float number in
57/// JSON is inifity.
58impl<'de> TryFrom<LazyValue<'de>> for Value {
59    type Error = crate::Error;
60    fn try_from(value: LazyValue<'de>) -> Result<Self, Self::Error> {
61        crate::from_str(value.as_raw_str())
62    }
63}