tonic/
extensions.rs

1use std::fmt;
2
3/// A type map of protocol extensions.
4///
5/// `Extensions` can be used by [`Interceptor`] and [`Request`] to store extra data derived from
6/// the underlying protocol.
7///
8/// [`Interceptor`]: crate::service::Interceptor
9/// [`Request`]: crate::Request
10pub struct Extensions {
11    inner: http::Extensions,
12}
13
14impl Extensions {
15    pub(crate) fn new() -> Self {
16        Self {
17            inner: http::Extensions::new(),
18        }
19    }
20
21    /// Insert a type into this `Extensions`.
22    ///
23    /// If a extension of this type already existed, it will
24    /// be returned.
25    #[inline]
26    pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
27        self.inner.insert(val)
28    }
29
30    /// Get a reference to a type previously inserted on this `Extensions`.
31    #[inline]
32    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
33        self.inner.get()
34    }
35
36    /// Get a mutable reference to a type previously inserted on this `Extensions`.
37    #[inline]
38    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
39        self.inner.get_mut()
40    }
41
42    /// Remove a type from this `Extensions`.
43    ///
44    /// If a extension of this type existed, it will be returned.
45    #[inline]
46    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
47        self.inner.remove()
48    }
49
50    /// Clear the `Extensions` of all inserted extensions.
51    #[inline]
52    pub fn clear(&mut self) {
53        self.inner.clear()
54    }
55
56    #[inline]
57    pub(crate) fn from_http(http: http::Extensions) -> Self {
58        Self { inner: http }
59    }
60
61    #[inline]
62    pub(crate) fn into_http(self) -> http::Extensions {
63        self.inner
64    }
65}
66
67impl fmt::Debug for Extensions {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.debug_struct("Extensions").finish()
70    }
71}