Skip to main content

rpc_api/
response.rs

1//! Zero-copy RPC response wrapper.
2
3/// Response from an RPC call. Wraps the raw record buffer and payload
4/// offset, providing zero-copy access to the payload via `Deref<Target = [u8]>`.
5///
6/// The caller deserializes directly from `&*response` without any copy.
7#[derive(Clone)]
8pub struct RpcResponse {
9    buf: Vec<u8>,
10    offset: usize,
11}
12
13impl RpcResponse {
14    /// Create a response from a payload Vec with no header (offset 0).
15    pub fn from_payload(payload: Vec<u8>) -> Self {
16        Self {
17            buf: payload,
18            offset: 0,
19        }
20    }
21
22    /// Create a response from a raw record buffer and the byte offset where
23    /// the payload begins.
24    ///
25    /// This is driver plumbing, not part of the supported API; use
26    /// [`from_payload`](Self::from_payload) to construct responses in tests
27    /// and mocks.
28    #[doc(hidden)]
29    pub fn from_record(buf: Vec<u8>, offset: usize) -> Self {
30        debug_assert!(offset <= buf.len());
31        Self { buf, offset }
32    }
33}
34
35impl std::ops::Deref for RpcResponse {
36    type Target = [u8];
37    fn deref(&self) -> &[u8] {
38        &self.buf[self.offset..]
39    }
40}
41
42impl AsRef<[u8]> for RpcResponse {
43    fn as_ref(&self) -> &[u8] {
44        self
45    }
46}
47
48impl PartialEq<[u8]> for RpcResponse {
49    fn eq(&self, other: &[u8]) -> bool {
50        &**self == other
51    }
52}
53
54impl<const N: usize> PartialEq<[u8; N]> for RpcResponse {
55    fn eq(&self, other: &[u8; N]) -> bool {
56        &**self == other
57    }
58}
59
60impl<const N: usize> PartialEq<&[u8; N]> for RpcResponse {
61    fn eq(&self, other: &&[u8; N]) -> bool {
62        &**self == *other
63    }
64}
65
66impl PartialEq<&[u8]> for RpcResponse {
67    fn eq(&self, other: &&[u8]) -> bool {
68        &**self == *other
69    }
70}
71
72impl PartialEq<Vec<u8>> for RpcResponse {
73    fn eq(&self, other: &Vec<u8>) -> bool {
74        &**self == other.as_slice()
75    }
76}
77
78impl PartialEq for RpcResponse {
79    fn eq(&self, other: &Self) -> bool {
80        **self == **other
81    }
82}
83
84impl Eq for RpcResponse {}
85
86impl std::fmt::Debug for RpcResponse {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.debug_struct("RpcResponse")
89            .field("len", &self.len())
90            .finish()
91    }
92}