distant_net/common/packet/
value.rs

1use std::borrow::Cow;
2use std::io;
3use std::ops::{Deref, DerefMut};
4
5use serde::de::DeserializeOwned;
6use serde::{Deserialize, Serialize};
7
8use crate::common::utils;
9
10/// Generic value type for data passed through header.
11#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct Value(serde_json::Value);
14
15impl Value {
16    /// Creates a new [`Value`] by converting `value` to the underlying type.
17    pub fn new(value: impl Into<serde_json::Value>) -> Self {
18        Self(value.into())
19    }
20
21    /// Serializes the value into bytes.
22    pub fn to_vec(&self) -> io::Result<Vec<u8>> {
23        utils::serialize_to_vec(self)
24    }
25
26    /// Deserializes the value from bytes.
27    pub fn from_slice(slice: &[u8]) -> io::Result<Self> {
28        utils::deserialize_from_slice(slice)
29    }
30
31    /// Attempts to convert this generic value to a specific type.
32    pub fn cast_as<T>(self) -> io::Result<T>
33    where
34        T: DeserializeOwned,
35    {
36        serde_json::from_value(self.0).map_err(|x| io::Error::new(io::ErrorKind::InvalidData, x))
37    }
38}
39
40impl Deref for Value {
41    type Target = serde_json::Value;
42
43    fn deref(&self) -> &Self::Target {
44        &self.0
45    }
46}
47
48impl DerefMut for Value {
49    fn deref_mut(&mut self) -> &mut Self::Target {
50        &mut self.0
51    }
52}
53
54macro_rules! impl_from {
55    ($($type:ty),+) => {
56        $(
57            impl From<$type> for Value {
58                fn from(x: $type) -> Self {
59                    Self(From::from(x))
60                }
61            }
62        )+
63    };
64}
65
66impl_from!(
67    (),
68    i8, i16, i32, i64, isize,
69    u8, u16, u32, u64, usize,
70    f32, f64,
71    bool, String, serde_json::Number,
72    serde_json::Map<String, serde_json::Value>
73);
74
75impl<'a, T> From<&'a [T]> for Value
76where
77    T: Clone + Into<serde_json::Value>,
78{
79    fn from(x: &'a [T]) -> Self {
80        Self(From::from(x))
81    }
82}
83
84impl<'a> From<&'a str> for Value {
85    fn from(x: &'a str) -> Self {
86        Self(From::from(x))
87    }
88}
89
90impl<'a> From<Cow<'a, str>> for Value {
91    fn from(x: Cow<'a, str>) -> Self {
92        Self(From::from(x))
93    }
94}
95
96impl<T> From<Option<T>> for Value
97where
98    T: Into<serde_json::Value>,
99{
100    fn from(x: Option<T>) -> Self {
101        Self(From::from(x))
102    }
103}
104
105impl<T> From<Vec<T>> for Value
106where
107    T: Into<serde_json::Value>,
108{
109    fn from(x: Vec<T>) -> Self {
110        Self(From::from(x))
111    }
112}