Skip to main content

grpc_core/
response.rs

1//! Response messages and their initial application metadata.
2
3use crate::Metadata;
4
5/// A response message with initial application metadata.
6///
7/// This envelope does not represent terminal gRPC status or trailing metadata.
8/// Those belong to the RPC stream lifecycle.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct Response<T> {
11    metadata: Metadata,
12    message: T,
13}
14
15impl<T> Response<T> {
16    /// Wraps a message with empty initial metadata.
17    #[must_use]
18    pub fn new(message: T) -> Self {
19        Self::from_parts(Metadata::new(), message)
20    }
21
22    /// Combines initial application metadata and a message.
23    #[must_use]
24    pub const fn from_parts(metadata: Metadata, message: T) -> Self {
25        Self { metadata, message }
26    }
27
28    /// Borrows the initial application metadata.
29    #[must_use]
30    pub const fn metadata(&self) -> &Metadata {
31        &self.metadata
32    }
33
34    /// Mutably borrows the initial application metadata.
35    pub const fn metadata_mut(&mut self) -> &mut Metadata {
36        &mut self.metadata
37    }
38
39    /// Borrows the response message.
40    #[must_use]
41    pub const fn get_ref(&self) -> &T {
42        &self.message
43    }
44
45    /// Mutably borrows the response message.
46    pub const fn get_mut(&mut self) -> &mut T {
47        &mut self.message
48    }
49
50    /// Consumes the envelope, returning initial metadata and the message.
51    #[must_use]
52    pub fn into_parts(self) -> (Metadata, T) {
53        (self.metadata, self.message)
54    }
55
56    /// Transforms the message while preserving initial application metadata.
57    #[must_use]
58    pub fn map<U>(self, transform: impl FnOnce(T) -> U) -> Response<U> {
59        Response::from_parts(self.metadata, transform(self.message))
60    }
61}