Skip to main content

opensearch_dsl/search/response/
source.rs

1use serde::de::DeserializeOwned;
2use serde_json::{value::RawValue, Value};
3
4use crate::util::ShouldSkip;
5
6/// Document source with delayed deserialization
7#[derive(Clone, Default, Serialize, Deserialize)]
8pub struct Source(Box<RawValue>);
9
10impl std::fmt::Debug for Source {
11    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12        self.0.fmt(f)
13    }
14}
15
16impl std::fmt::Display for Source {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        self.0.fmt(f)
19    }
20}
21
22impl PartialEq for Source {
23    fn eq(&self, other: &Self) -> bool {
24        self.0.get() == other.0.get()
25    }
26}
27
28impl ShouldSkip for Source {
29    fn should_skip(&self) -> bool {
30        self.eq(&Source::default())
31    }
32}
33
34impl Source {
35    /// Parses document source into a concrete type
36    pub fn parse<T>(&self) -> Result<T, serde_json::Error>
37    where
38        T: DeserializeOwned,
39    {
40        serde_json::from_str(self.0.get())
41    }
42
43    /// Creates source from a string
44    pub fn from_string(value: String) -> Result<Self, serde_json::Error> {
45        RawValue::from_string(value).map(Self)
46    }
47}
48
49impl From<Value> for Source {
50    /// Creates source from a [Value]
51    ///
52    /// Calling expect here because [Value] always represents a valid JSON and it
53    /// _should be safe_ to do so.
54    fn from(value: Value) -> Self {
55        Self(RawValue::from_string(format!("{value}")).expect("valid json"))
56    }
57}
58
59impl From<Box<RawValue>> for Source {
60    fn from(value: Box<RawValue>) -> Self {
61        Self(value)
62    }
63}
64
65impl<'a> From<&'a RawValue> for Source {
66    fn from(value: &'a RawValue) -> Self {
67        Self(value.to_owned())
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn creates_from_json_value() {
77        let _ = Source::from(json!({"key": "value"}));
78        let _ = Source::from(json!({"key": ["value", 1, 1.2, true, null, {"key2": "value2"}]}));
79        let _ = Source::from(json!(["one", 2, 3.0, false, null, {}]));
80    }
81}