From 25495947b43da6cdf08c149d1ce6724cc69dc864 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Mon, 11 Dec 2023 14:54:12 -0800 Subject: [PATCH] BoxedTransport: Add methods to downcast to a specific transport type These functions are useful for getting access to an application-specific custom transport type that has additional methods. --- http/src/transport/boxed_transport.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/http/src/transport/boxed_transport.rs b/http/src/transport/boxed_transport.rs index 61fc4b4090..9c3982b4d9 100644 --- a/http/src/transport/boxed_transport.rs +++ b/http/src/transport/boxed_transport.rs @@ -14,6 +14,8 @@ use trillium_macros::{AsyncRead, AsyncWrite}; pub(crate) trait AnyTransport: Transport + Any { fn as_box_any(self: Box) -> Box; fn as_box_transport(self: Box) -> Box; + fn as_any(&self) -> &dyn Any; + fn as_mut_any(&mut self) -> &mut dyn Any; fn as_transport(&self) -> &dyn Transport; } impl AnyTransport for T { @@ -23,6 +25,12 @@ impl AnyTransport for T { fn as_box_transport(self: Box) -> Box { self } + fn as_any(&self) -> &dyn Any { + self + } + fn as_mut_any(&mut self) -> &mut dyn Any { + self + } fn as_transport(&self) -> &dyn Transport { self } @@ -85,6 +93,24 @@ impl BoxedTransport { pub fn downcast(self) -> Option> { self.0.as_box_any().downcast().ok() } + + /** + Attempt to get a reference to the trait object as a specific transport type T. This will only + succeed if T is the type that was originally passed to [`BoxedTransport::new`], and will return + None otherwise + */ + pub fn downcast_ref(&self) -> Option<&T> { + self.0.as_any().downcast_ref() + } + + /** + Attempt to get a mutable reference to the trait object as a specific transport type T. This + will only succeed if T is the type that was originally passed to [`BoxedTransport::new`], and + will return None otherwise + */ + pub fn downcast_mut(&mut self) -> Option<&mut T> { + self.0.as_mut_any().downcast_mut() + } } impl Deref for BoxedTransport {