Skip to content

Commit

Permalink
BoxedTransport: Add methods to downcast to a specific transport type
Browse files Browse the repository at this point in the history
These functions are useful for getting access to an application-specific
custom transport type that has additional methods.
  • Loading branch information
joshtriplett committed Dec 20, 2023
1 parent b56ee42 commit 2549594
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions http/src/transport/boxed_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use trillium_macros::{AsyncRead, AsyncWrite};
pub(crate) trait AnyTransport: Transport + Any {
fn as_box_any(self: Box<Self>) -> Box<dyn Any>;
fn as_box_transport(self: Box<Self>) -> Box<dyn Transport>;
fn as_any(&self) -> &dyn Any;
fn as_mut_any(&mut self) -> &mut dyn Any;
fn as_transport(&self) -> &dyn Transport;
}
impl<T: Transport + Any> AnyTransport for T {
Expand All @@ -23,6 +25,12 @@ impl<T: Transport + Any> AnyTransport for T {
fn as_box_transport(self: Box<Self>) -> Box<dyn Transport> {
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
}
Expand Down Expand Up @@ -85,6 +93,24 @@ impl BoxedTransport {
pub fn downcast<T: 'static>(self) -> Option<Box<T>> {
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<T: Transport>(&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<T: Transport>(&mut self) -> Option<&mut T> {
self.0.as_mut_any().downcast_mut()
}
}

impl Deref for BoxedTransport {
Expand Down

0 comments on commit 2549594

Please sign in to comment.