Skip to main content

plexus_client/
wire_result.rs

1//! The wire encoding of a Result item: `Ok(t)` ⇄ `{"ok": t}`,
2//! `Err(e)` ⇄ `{"err": e}`.
3//!
4//! A method that returns `Result<T, E>` (or streams `Result` items) sends
5//! each item as data — an err is the activation saying no, not the call
6//! failing — and this is its shape. Use it as a serde `with` module:
7//!
8//! ```
9//! use plexus_client::wire_result;
10//! use serde::{Deserialize, Serialize};
11//!
12//! #[derive(Debug, PartialEq, Serialize, Deserialize)]
13//! struct Wrapped(#[serde(with = "wire_result")] Result<u32, String>);
14//!
15//! let ok = serde_json::to_value(Wrapped(Ok(7))).unwrap();
16//! assert_eq!(ok, serde_json::json!({"ok": 7}));
17//!
18//! let err: Wrapped = serde_json::from_value(serde_json::json!({"err": "no"})).unwrap();
19//! assert_eq!(err, Wrapped(Err("no".into())));
20//! ```
21//!
22//! or call [`serialize`] / [`deserialize`] directly with any serde
23//! (de)serializer — a `serde_json::Value` is one. [`from_value`] and
24//! [`to_value`] are those two for a data frame's `content`; `from_value` is
25//! the item decoder a generated client hands
26//! [`MethodStream`](crate::MethodStream) for a Result method.
27//!
28//! Decoding accepts exactly an object with one key, `ok` or `err`; anything
29//! else (another key, both keys, no key, a non-object) is an error whose
30//! message names both keys.
31//!
32//! Works inside adjacently-tagged enums
33//! (`#[serde(tag = "method", content = "event")]`) on a newtype variant —
34//! the shape of the derived `{Ns}Event` aggregate.
35
36use std::fmt;
37use std::marker::PhantomData;
38
39use serde::de::{self, IgnoredAny, MapAccess, Visitor};
40use serde::ser::SerializeMap;
41use serde::{Deserialize, Deserializer, Serialize, Serializer};
42
43const OK: &str = "ok";
44const ERR: &str = "err";
45const EXPECTED: &str = "an object with exactly one key, `ok` or `err`";
46
47/// `Ok(t)` → `{"ok": t}`, `Err(e)` → `{"err": e}`.
48pub fn serialize<T, E, S>(value: &Result<T, E>, serializer: S) -> Result<S::Ok, S::Error>
49where
50    T: Serialize,
51    E: Serialize,
52    S: Serializer,
53{
54    let mut map = serializer.serialize_map(Some(1))?;
55    match value {
56        Ok(t) => map.serialize_entry(OK, t)?,
57        Err(e) => map.serialize_entry(ERR, e)?,
58    }
59    map.end()
60}
61
62/// `{"ok": t}` → `Ok(t)`, `{"err": e}` → `Err(e)`; any other shape is an
63/// error naming both keys.
64pub fn deserialize<'de, T, E, D>(deserializer: D) -> Result<Result<T, E>, D::Error>
65where
66    T: Deserialize<'de>,
67    E: Deserialize<'de>,
68    D: Deserializer<'de>,
69{
70    deserializer.deserialize_map(ResultVisitor(PhantomData))
71}
72
73/// A data frame's `content` → a Result item: `{"ok": t}` → `Ok(t)`,
74/// `{"err": e}` → `Err(e)`. As a [`Decoder`](crate::Decoder), what a
75/// generated client decodes a Result method's items with.
76pub fn from_value<T, E>(content: serde_json::Value) -> Result<Result<T, E>, serde_json::Error>
77where
78    T: serde::de::DeserializeOwned,
79    E: serde::de::DeserializeOwned,
80{
81    deserialize(content)
82}
83
84/// [`from_value`] from a data frame's [`Content`](crate::Content): straight
85/// from the wire's text where the transport kept it (PERF.115-36). What a
86/// generated client decodes a Result method's items with.
87pub fn from_content<T, E>(content: crate::Content) -> Result<Result<T, E>, serde_json::Error>
88where
89    T: serde::de::DeserializeOwned,
90    E: serde::de::DeserializeOwned,
91{
92    struct Wire<T, E>(Result<T, E>);
93    impl<'de, T: Deserialize<'de>, E: Deserialize<'de>> Deserialize<'de> for Wire<T, E> {
94        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
95            deserialize(d).map(Wire)
96        }
97    }
98    content.decode::<Wire<T, E>>().map(|w| w.0)
99}
100
101/// A Result item → a data frame's `content`: `Ok(t)` → `{"ok": t}`,
102/// `Err(e)` → `{"err": e}`. What a test scripts a Result method's items with.
103pub fn to_value<T, E>(item: &Result<T, E>) -> Result<serde_json::Value, serde_json::Error>
104where
105    T: Serialize,
106    E: Serialize,
107{
108    serialize(item, serde_json::value::Serializer)
109}
110
111struct ResultVisitor<T, E>(PhantomData<fn() -> (T, E)>);
112
113impl<'de, T, E> Visitor<'de> for ResultVisitor<T, E>
114where
115    T: Deserialize<'de>,
116    E: Deserialize<'de>,
117{
118    type Value = Result<T, E>;
119
120    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(EXPECTED)
122    }
123
124    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
125        let value = match map.next_key::<Key>()? {
126            Some(Key::Ok) => Ok(map.next_value::<T>()?),
127            Some(Key::Err) => Err(map.next_value::<E>()?),
128            None => {
129                return Err(de::Error::custom(format_args!(
130                    "expected {EXPECTED}, found an empty object"
131                )))
132            }
133        };
134        if map.next_key::<IgnoredAny>()?.is_some() {
135            return Err(de::Error::custom(format_args!(
136                "expected {EXPECTED}, found more than one key"
137            )));
138        }
139        Ok(value)
140    }
141}
142
143/// The one key of a Result item.
144enum Key {
145    Ok,
146    Err,
147}
148
149impl<'de> Deserialize<'de> for Key {
150    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
151        deserializer.deserialize_identifier(KeyVisitor)
152    }
153}
154
155struct KeyVisitor;
156
157impl<'de> Visitor<'de> for KeyVisitor {
158    type Value = Key;
159
160    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        f.write_str("the key `ok` or `err`")
162    }
163
164    fn visit_str<X: de::Error>(self, key: &str) -> Result<Key, X> {
165        match key {
166            OK => Ok(Key::Ok),
167            ERR => Ok(Key::Err),
168            other => Err(X::custom(format_args!(
169                "expected {EXPECTED}, found key `{other}`"
170            ))),
171        }
172    }
173
174    fn visit_bytes<X: de::Error>(self, key: &[u8]) -> Result<Key, X> {
175        match key {
176            b"ok" => Ok(Key::Ok),
177            b"err" => Ok(Key::Err),
178            other => Err(X::custom(format_args!(
179                "expected {EXPECTED}, found key `{}`",
180                String::from_utf8_lossy(other)
181            ))),
182        }
183    }
184}