@@ -84,6 +84,61 @@ impl fmt::Debug for Box<NetworkStream + Send> {
84
84
}
85
85
}
86
86
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
+
87
142
impl NetworkStream + Send {
88
143
unsafe fn downcast_ref_unchecked < T : ' static > ( & self ) -> & T {
89
144
mem:: transmute ( traitobject:: data ( self ) )
0 commit comments