Skip to main content

khive_wire_protocol/
opaque.rs

1//! Owned JSON tokens for ADR-137 Amendment 1 Decision 9.
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use serde_json::{value::RawValue, Value};
5
6/// An immutable opaque JSON value carried by a response or event.
7///
8/// Received values retain their original JSON token. Locally constructed
9/// `Value`s keep serde_json's normal serialization. Parsing is explicit and
10/// fallible; no parsed view or caller buffer is retained alongside the token.
11#[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    /// Return an independent parsed value, without changing this token.
22    ///
23    /// Received numbers can exceed serde_json's representable range, so this
24    /// operation can fail even though decode and re-encode remain valid.
25    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    /// The original JSON token for a received value; `None` for local values.
33    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            // RawValue is validated JSON with leading/trailing whitespace
44            // outside its token removed. No numeric projection is needed.
45            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;