1 use 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 10 #[derive(Default)] 11 pub struct Extensions { 12 inner: http::Extensions, 13 } 14 15 impl Extensions { new() -> Self16 pub(crate) fn new() -> Self { 17 Self { 18 inner: http::Extensions::new(), 19 } 20 } 21 22 /// Insert a type into this `Extensions`. 23 /// 24 /// If a extension of this type already existed, it will 25 /// be returned. 26 #[inline] insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T>27 pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> { 28 self.inner.insert(val) 29 } 30 31 /// Get a reference to a type previously inserted on this `Extensions`. 32 #[inline] get<T: Send + Sync + 'static>(&self) -> Option<&T>33 pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> { 34 self.inner.get() 35 } 36 37 /// Get a mutable reference to a type previously inserted on this `Extensions`. 38 #[inline] get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>39 pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> { 40 self.inner.get_mut() 41 } 42 43 /// Remove a type from this `Extensions`. 44 /// 45 /// If a extension of this type existed, it will be returned. 46 #[inline] remove<T: Send + Sync + 'static>(&mut self) -> Option<T>47 pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> { 48 self.inner.remove() 49 } 50 51 /// Clear the `Extensions` of all inserted extensions. 52 #[inline] clear(&mut self)53 pub fn clear(&mut self) { 54 self.inner.clear() 55 } 56 57 #[inline] from_http(http: http::Extensions) -> Self58 pub(crate) fn from_http(http: http::Extensions) -> Self { 59 Self { inner: http } 60 } 61 62 /// Convert to `http::Extensions` and consume self. 63 #[inline] into_http(self) -> http::Extensions64 pub fn into_http(self) -> http::Extensions { 65 self.inner 66 } 67 } 68 69 impl fmt::Debug for Extensions { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 71 f.debug_struct("Extensions").finish() 72 } 73 } 74 75 /// A gRPC Method info extension. 76 #[derive(Debug, Clone)] 77 pub struct GrpcMethod { 78 service: &'static str, 79 method: &'static str, 80 } 81 82 impl GrpcMethod { 83 /// Create a new `GrpcMethod` extension. 84 #[doc(hidden)] new(service: &'static str, method: &'static str) -> Self85 pub fn new(service: &'static str, method: &'static str) -> Self { 86 Self { service, method } 87 } 88 89 /// gRPC service name service(&self) -> &str90 pub fn service(&self) -> &str { 91 self.service 92 } 93 /// gRPC method name method(&self) -> &str94 pub fn method(&self) -> &str { 95 self.method 96 } 97 } 98