1use crate::{Response, ResponsePayload, RpcError, RpcRecv};
2use serde_json::value::RawValue;
3use std::{any::TypeId, borrow::Borrow};
4
5pub type RpcResult<T, E, ErrResp = Box<RawValue>> = Result<T, RpcError<E, ErrResp>>;
18
19pub type BorrowedRpcResult<'a, E> = RpcResult<&'a RawValue, E, &'a RawValue>;
21
22pub fn transform_response<T, E, ErrResp>(response: Response<T, ErrResp>) -> RpcResult<T, E, ErrResp>
26where
27 ErrResp: RpcRecv,
28{
29 match response {
30 Response { payload: ResponsePayload::Failure(err_resp), .. } => {
31 Err(RpcError::err_resp(err_resp))
32 }
33 Response { payload: ResponsePayload::Success(result), .. } => Ok(result),
34 }
35}
36
37pub fn transform_result<T, E, ErrResp>(
41 response: Result<Response<T, ErrResp>, E>,
42) -> Result<T, RpcError<E, ErrResp>>
43where
44 ErrResp: RpcRecv,
45{
46 match response {
47 Ok(resp) => transform_response(resp),
48 Err(e) => Err(RpcError::Transport(e)),
49 }
50}
51
52pub fn try_deserialize_ok<J, T, E, ErrResp>(
54 result: RpcResult<J, E, ErrResp>,
55) -> RpcResult<T, E, ErrResp>
56where
57 J: Borrow<RawValue> + 'static,
58 T: RpcRecv,
59 ErrResp: RpcRecv,
60{
61 let json = result?;
62
63 if TypeId::of::<J>() == TypeId::of::<Box<RawValue>>()
67 && TypeId::of::<T>() == TypeId::of::<Box<RawValue>>()
68 {
69 let json = std::mem::ManuallyDrop::new(json);
72 return Ok(unsafe { std::mem::transmute_copy::<J, T>(&json) });
73 }
74
75 let _guard = debug_span!("deserialize_response", ty=%std::any::type_name::<T>()).entered();
76 let json = json.borrow().get();
77 trace!(%json, "deserializing");
78 serde_json::from_str(json)
79 .inspect(|response| trace!(?response, "deserialized"))
80 .inspect_err(|err| trace!(?err, "failed to deserialize"))
81 .map_err(|err| RpcError::deser_err(err, json))
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use serde_json::value::to_raw_value;
88
89 #[test]
90 fn raw_value_success_returns_payload_without_reencoding() {
91 let src = "{ \"a\" :1,\"b\": [ 2 ,3 ] }";
94 let raw = RawValue::from_string(src.to_owned()).unwrap();
95 let ptr = raw.get().as_ptr();
96 let input: RpcResult<Box<RawValue>, (), Box<RawValue>> = Ok(raw);
97
98 let out = try_deserialize_ok::<_, Box<RawValue>, (), Box<RawValue>>(input).unwrap();
99
100 assert_eq!(out.get(), src);
101 assert_eq!(out.get().as_ptr(), ptr);
103 }
104
105 #[test]
106 fn generic_deserialize_path_unchanged() {
107 let raw = to_raw_value(&42u64).unwrap();
108 let input: RpcResult<Box<RawValue>, (), Box<RawValue>> = Ok(raw);
109 let out = try_deserialize_ok::<_, u64, (), Box<RawValue>>(input).unwrap();
110 assert_eq!(out, 42);
111 }
112}