Skip to content

Commit 1a91835

Browse files
committed
feat(net): impl downcast methods for NetworkStream (without + Send)
Closes #521
1 parent 8791a7e commit 1a91835

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/net.rs

+55
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,61 @@ impl fmt::Debug for Box<NetworkStream + Send> {
8484
}
8585
}
8686

87+
impl NetworkStream {
88+
unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T {
89+
mem::transmute(traitobject::data(self))
90+
}
91+
92+
unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T {
93+
mem::transmute(traitobject::data_mut(self))
94+
}
95+
96+
unsafe fn downcast_unchecked<T: 'static>(self: Box<NetworkStream>) -> Box<T> {
97+
let raw: *mut NetworkStream = mem::transmute(self);
98+
mem::transmute(traitobject::data_mut(raw))
99+
}
100+
}
101+
102+
impl NetworkStream {
103+
/// Is the underlying type in this trait object a T?
104+
#[inline]
105+
pub fn is<T: Any>(&self) -> bool {
106+
(*self).get_type() == TypeId::of::<T>()
107+
}
108+
109+
/// If the underlying type is T, get a reference to the contained data.
110+
#[inline]
111+
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
112+
if self.is::<T>() {
113+
Some(unsafe { self.downcast_ref_unchecked() })
114+
} else {
115+
None
116+
}
117+
}
118+
119+
/// If the underlying type is T, get a mutable reference to the contained
120+
/// data.
121+
#[inline]
122+
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
123+
if self.is::<T>() {
124+
Some(unsafe { self.downcast_mut_unchecked() })
125+
} else {
126+
None
127+
}
128+
}
129+
130+
/// If the underlying type is T, extract it.
131+
#[inline]
132+
pub fn downcast<T: Any>(self: Box<NetworkStream>)
133+
-> Result<Box<T>, Box<NetworkStream>> {
134+
if self.is::<T>() {
135+
Ok(unsafe { self.downcast_unchecked() })
136+
} else {
137+
Err(self)
138+
}
139+
}
140+
}
141+
87142
impl NetworkStream + Send {
88143
unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T {
89144
mem::transmute(traitobject::data(self))

0 commit comments

Comments
 (0)