khive_wire_protocol/
opaque.rs1use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use serde_json::{value::RawValue, Value};
5
6#[derive(Clone, Debug)]
12pub struct OpaqueValue(Representation);
13
14#[derive(Clone, Debug)]
15enum Representation {
16 Local(Value),
17 Received(Box<RawValue>),
18}
19
20impl OpaqueValue {
21 pub fn to_value(&self) -> serde_json::Result<Value> {
26 match &self.0 {
27 Representation::Local(value) => Ok(value.clone()),
28 Representation::Received(raw) => serde_json::from_str(raw.get()),
29 }
30 }
31
32 pub fn received_json(&self) -> Option<&str> {
34 match &self.0 {
35 Representation::Local(_) => None,
36 Representation::Received(raw) => Some(raw.get()),
37 }
38 }
39
40 pub(crate) fn is_object(&self) -> bool {
41 match &self.0 {
42 Representation::Local(value) => value.is_object(),
43 Representation::Received(raw) => raw.get().as_bytes().first() == Some(&b'{'),
46 }
47 }
48}
49
50impl From<Value> for OpaqueValue {
51 fn from(value: Value) -> Self {
52 Self(Representation::Local(value))
53 }
54}
55
56impl Serialize for OpaqueValue {
57 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
58 match &self.0 {
59 Representation::Local(value) => value.serialize(serializer),
60 Representation::Received(raw) => raw.serialize(serializer),
61 }
62 }
63}
64
65impl<'de> Deserialize<'de> for OpaqueValue {
66 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
67 Box::<RawValue>::deserialize(deserializer).map(|raw| Self(Representation::Received(raw)))
68 }
69}
70
71impl PartialEq for OpaqueValue {
72 fn eq(&self, other: &Self) -> bool {
73 if let (Representation::Local(left), Representation::Local(right)) = (&self.0, &other.0) {
74 return left == right;
75 }
76 match (self.to_value(), other.to_value()) {
77 (Ok(left), Ok(right)) => left == right,
78 (Err(_), Err(_)) => match (&self.0, &other.0) {
79 (Representation::Received(left), Representation::Received(right)) => {
80 left.get() == right.get()
81 }
82 _ => false,
83 },
84 _ => false,
85 }
86 }
87}
88
89#[cfg(test)]
90#[path = "opaque_tests.rs"]
91mod tests;