1#![deny(unsafe_code,rustdoc::bare_urls)]
2#![cfg_attr(not(feature = "std"), no_std)]
3#[doc(hidden)]
162#[cfg(not(feature = "std"))]
163pub extern crate core as __std;
164#[doc(hidden)]
165#[cfg(feature = "std")]
166pub extern crate std as __std;
167#[doc(hidden)]
168pub extern crate alloc as __alloc;
169
170use __std::any::Any;
171use __alloc::{boxed::Box, rc::Rc, sync::Arc};
172
173pub trait Downcast: Any {
175 fn into_any(self: Box<Self>) -> Box<dyn Any>;
178 fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any>;
181 fn as_any(&self) -> &dyn Any;
184 fn as_any_mut(&mut self) -> &mut dyn Any;
187}
188
189impl<T: Any> Downcast for T {
190 fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
191 fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any> { self }
192 fn as_any(&self) -> &dyn Any { self }
193 fn as_any_mut(&mut self) -> &mut dyn Any { self }
194}
195
196pub trait DowncastSync: Downcast + Send + Sync {
198 fn into_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
201}
202
203impl<T: Any + Send + Sync> DowncastSync for T {
204 fn into_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> { self }
205}
206
207#[macro_export(local_inner_macros)]
213macro_rules! impl_downcast {
214 (@impl_full
215 $trait_:ident [$($param_types:tt)*]
216 for [$($forall_types:ident),*]
217 where [$($preds:tt)*]
218 ) => {
219 impl_downcast! {
220 @inject_where
221 [impl<$($forall_types),*> dyn $trait_<$($param_types)*>]
222 types [$($forall_types),*]
223 where [$($preds)*]
224 [{
225 impl_downcast! { @impl_body $trait_ [$($param_types)*] }
226 }]
227 }
228 };
229
230 (@impl_full_sync
231 $trait_:ident [$($param_types:tt)*]
232 for [$($forall_types:ident),*]
233 where [$($preds:tt)*]
234 ) => {
235 impl_downcast! {
236 @inject_where
237 [impl<$($forall_types),*> dyn $trait_<$($param_types)*>]
238 types [$($forall_types),*]
239 where [$($preds)*]
240 [{
241 impl_downcast! { @impl_body $trait_ [$($param_types)*] }
242 impl_downcast! { @impl_body_sync $trait_ [$($param_types)*] }
243 }]
244 }
245 };
246
247 (@impl_body $trait_:ident [$($types:tt)*]) => {
248 #[inline]
250 pub fn is<__T: $trait_<$($types)*>>(&self) -> bool {
251 $crate::Downcast::as_any(self).is::<__T>()
252 }
253 #[inline]
256 pub fn downcast<__T: $trait_<$($types)*>>(
257 self: $crate::__alloc::boxed::Box<Self>
258 ) -> $crate::__std::result::Result<$crate::__alloc::boxed::Box<__T>, $crate::__alloc::boxed::Box<Self>> {
259 if self.is::<__T>() {
260 Ok($crate::Downcast::into_any(self).downcast::<__T>().unwrap())
261 } else {
262 Err(self)
263 }
264 }
265 #[inline]
268 pub fn downcast_rc<__T: $trait_<$($types)*>>(
269 self: $crate::__alloc::rc::Rc<Self>
270 ) -> $crate::__std::result::Result<$crate::__alloc::rc::Rc<__T>, $crate::__alloc::rc::Rc<Self>> {
271 if self.is::<__T>() {
272 Ok($crate::Downcast::into_any_rc(self).downcast::<__T>().unwrap())
273 } else {
274 Err(self)
275 }
276 }
277 #[inline]
280 pub fn downcast_ref<__T: $trait_<$($types)*>>(&self) -> $crate::__std::option::Option<&__T> {
281 $crate::Downcast::as_any(self).downcast_ref::<__T>()
282 }
283 #[inline]
286 pub fn downcast_mut<__T: $trait_<$($types)*>>(&mut self) -> $crate::__std::option::Option<&mut __T> {
287 $crate::Downcast::as_any_mut(self).downcast_mut::<__T>()
288 }
289 };
290
291 (@impl_body_sync $trait_:ident [$($types:tt)*]) => {
292 #[inline]
295 pub fn downcast_arc<__T: $trait_<$($types)*> + $crate::__std::any::Any + $crate::__std::marker::Send + $crate::__std::marker::Sync>(
296 self: $crate::__alloc::sync::Arc<Self>,
297 ) -> $crate::__std::result::Result<$crate::__alloc::sync::Arc<__T>, $crate::__alloc::sync::Arc<Self>>
298 {
299 if self.is::<__T>() {
300 Ok($crate::DowncastSync::into_any_arc(self).downcast::<__T>().unwrap())
301 } else {
302 Err(self)
303 }
304 }
305 };
306
307 (@inject_where [$($before:tt)*] types [] where [] [$($after:tt)*]) => {
308 impl_downcast! { @as_item $($before)* $($after)* }
309 };
310
311 (@inject_where [$($before:tt)*] types [$($types:ident),*] where [] [$($after:tt)*]) => {
312 impl_downcast! {
313 @as_item
314 $($before)*
315 where $( $types: $crate::__std::any::Any + 'static ),*
316 $($after)*
317 }
318 };
319 (@inject_where [$($before:tt)*] types [$($types:ident),*] where [$($preds:tt)+] [$($after:tt)*]) => {
320 impl_downcast! {
321 @as_item
322 $($before)*
323 where
324 $( $types: $crate::__std::any::Any + 'static, )*
325 $($preds)*
326 $($after)*
327 }
328 };
329
330 (@as_item $i:item) => { $i };
331
332 ($trait_:ident ) => { impl_downcast! { @impl_full $trait_ [] for [] where [] } };
334 ($trait_:ident <>) => { impl_downcast! { @impl_full $trait_ [] for [] where [] } };
335 (sync $trait_:ident ) => { impl_downcast! { @impl_full_sync $trait_ [] for [] where [] } };
336 (sync $trait_:ident <>) => { impl_downcast! { @impl_full_sync $trait_ [] for [] where [] } };
337 ($trait_:ident < $($types:ident),* >) => {
339 impl_downcast! { @impl_full $trait_ [$($types),*] for [$($types),*] where [] }
340 };
341 (sync $trait_:ident < $($types:ident),* >) => {
342 impl_downcast! { @impl_full_sync $trait_ [$($types),*] for [$($types),*] where [] }
343 };
344 ($trait_:ident < $($types:ident),* > where $($preds:tt)+) => {
346 impl_downcast! { @impl_full $trait_ [$($types),*] for [$($types),*] where [$($preds)*] }
347 };
348 (sync $trait_:ident < $($types:ident),* > where $($preds:tt)+) => {
349 impl_downcast! { @impl_full_sync $trait_ [$($types),*] for [$($types),*] where [$($preds)*] }
350 };
351 ($trait_:ident assoc $($atypes:ident),*) => {
353 impl_downcast! { @impl_full $trait_ [$($atypes = $atypes),*] for [$($atypes),*] where [] }
354 };
355 (sync $trait_:ident assoc $($atypes:ident),*) => {
356 impl_downcast! { @impl_full_sync $trait_ [$($atypes = $atypes),*] for [$($atypes),*] where [] }
357 };
358 ($trait_:ident assoc $($atypes:ident),* where $($preds:tt)+) => {
360 impl_downcast! { @impl_full $trait_ [$($atypes = $atypes),*] for [$($atypes),*] where [$($preds)*] }
361 };
362 (sync $trait_:ident assoc $($atypes:ident),* where $($preds:tt)+) => {
363 impl_downcast! { @impl_full_sync $trait_ [$($atypes = $atypes),*] for [$($atypes),*] where [$($preds)*] }
364 };
365 ($trait_:ident < $($types:ident),* > assoc $($atypes:ident),*) => {
367 impl_downcast! {
368 @impl_full
369 $trait_ [$($types),*, $($atypes = $atypes),*]
370 for [$($types),*, $($atypes),*]
371 where []
372 }
373 };
374 (sync $trait_:ident < $($types:ident),* > assoc $($atypes:ident),*) => {
375 impl_downcast! {
376 @impl_full_sync
377 $trait_ [$($types),*, $($atypes = $atypes),*]
378 for [$($types),*, $($atypes),*]
379 where []
380 }
381 };
382 ($trait_:ident < $($types:ident),* > assoc $($atypes:ident),* where $($preds:tt)+) => {
384 impl_downcast! {
385 @impl_full
386 $trait_ [$($types),*, $($atypes = $atypes),*]
387 for [$($types),*, $($atypes),*]
388 where [$($preds)*]
389 }
390 };
391 (sync $trait_:ident < $($types:ident),* > assoc $($atypes:ident),* where $($preds:tt)+) => {
392 impl_downcast! {
393 @impl_full_sync
394 $trait_ [$($types),*, $($atypes = $atypes),*]
395 for [$($types),*, $($atypes),*]
396 where [$($preds)*]
397 }
398 };
399 (concrete $trait_:ident < $($types:ident),* >) => {
401 impl_downcast! { @impl_full $trait_ [$($types),*] for [] where [] }
402 };
403 (sync concrete $trait_:ident < $($types:ident),* >) => {
404 impl_downcast! { @impl_full_sync $trait_ [$($types),*] for [] where [] }
405 };
406 (concrete $trait_:ident assoc $($atypes:ident = $aty:ty),*) => {
408 impl_downcast! { @impl_full $trait_ [$($atypes = $aty),*] for [] where [] }
409 };
410 (sync concrete $trait_:ident assoc $($atypes:ident = $aty:ty),*) => {
411 impl_downcast! { @impl_full_sync $trait_ [$($atypes = $aty),*] for [] where [] }
412 };
413 (concrete $trait_:ident < $($types:ident),* > assoc $($atypes:ident = $aty:ty),*) => {
415 impl_downcast! { @impl_full $trait_ [$($types),*, $($atypes = $aty),*] for [] where [] }
416 };
417 (sync concrete $trait_:ident < $($types:ident),* > assoc $($atypes:ident = $aty:ty),*) => {
418 impl_downcast! { @impl_full_sync $trait_ [$($types),*, $($atypes = $aty),*] for [] where [] }
419 };
420}
421
422
423#[cfg(test)]
424mod test {
425 macro_rules! test_mod {
426 (
427 $test_mod_name:ident,
428 trait $base_trait:path { $($base_impl:tt)* },
429 non_sync: { $($non_sync_def:tt)+ },
430 sync: { $($sync_def:tt)+ }
431 ) => {
432 test_mod! {
433 $test_mod_name,
434 trait $base_trait { $($base_impl:tt)* },
435 type dyn $base_trait,
436 non_sync: { $($non_sync_def)* },
437 sync: { $($sync_def)* }
438 }
439 };
440
441 (
442 $test_mod_name:ident,
443 trait $base_trait:path { $($base_impl:tt)* },
444 type $base_type:ty,
445 non_sync: { $($non_sync_def:tt)+ },
446 sync: { $($sync_def:tt)+ }
447 ) => {
448 mod $test_mod_name {
449 test_mod!(
450 @test
451 $test_mod_name,
452 test_name: test_non_sync,
453 trait $base_trait { $($base_impl)* },
454 type $base_type,
455 { $($non_sync_def)+ },
456 []);
457
458 test_mod!(
459 @test
460 $test_mod_name,
461 test_name: test_sync,
462 trait $base_trait { $($base_impl)* },
463 type $base_type,
464 { $($sync_def)+ },
465 [{
466 let arc: $crate::__alloc::sync::Arc<$base_type> = $crate::__alloc::sync::Arc::new(Foo(42));
468 let res = arc.downcast_arc::<Bar>();
469 assert!(res.is_err());
470 let arc = res.unwrap_err();
471 assert_eq!(
473 42, arc.downcast_arc::<Foo>().map_err(|_| "Shouldn't happen.").unwrap().0);
474 }]);
475 }
476 };
477
478 (
479 @test
480 $test_mod_name:ident,
481 test_name: $test_name:ident,
482 trait $base_trait:path { $($base_impl:tt)* },
483 type $base_type:ty,
484 { $($def:tt)+ },
485 [ $($more_tests:block)* ]
486 ) => {
487 #[test]
488 fn $test_name() {
489 #[allow(unused_imports)]
490 use super::super::{Downcast, DowncastSync};
491
492 #[allow(dead_code)] struct Any;
495 #[allow(dead_code)] struct Arc;
496 #[allow(dead_code)] struct Box;
497 #[allow(dead_code)] struct Option;
498 #[allow(dead_code)] struct Result;
499 #[allow(dead_code)] struct Rc;
500 #[allow(dead_code)] struct Send;
501 #[allow(dead_code)] struct Sync;
502
503 $($def)*
505
506 #[derive(Debug)]
508 struct Foo(u32);
509 impl $base_trait for Foo { $($base_impl)* }
510 #[derive(Debug)]
511 struct Bar(f64);
512 impl $base_trait for Bar { $($base_impl)* }
513
514 fn get_val(base: &$crate::__alloc::boxed::Box<$base_type>) -> u32 {
516 match base.downcast_ref::<Foo>() {
517 Some(val) => val.0,
518 None => 0
519 }
520 }
521 fn set_val(base: &mut $crate::__alloc::boxed::Box<$base_type>, val: u32) {
522 if let Some(foo) = base.downcast_mut::<Foo>() {
523 foo.0 = val;
524 }
525 }
526
527 let mut base: $crate::__alloc::boxed::Box<$base_type> = $crate::__alloc::boxed::Box::new(Foo(42));
528 assert_eq!(get_val(&base), 42);
529
530 if let Some(foo) = base.downcast_ref::<Foo>() {
532 assert_eq!(foo.0, 42);
533 } else if let Some(bar) = base.downcast_ref::<Bar>() {
534 assert_eq!(bar.0, 42.0);
535 }
536
537 set_val(&mut base, 6*9);
538 assert_eq!(get_val(&base), 6*9);
539
540 assert!(base.is::<Foo>());
541
542 let res = base.downcast::<Bar>();
544 assert!(res.is_err());
545 let base = res.unwrap_err();
546 assert_eq!(
548 6*9, base.downcast::<Foo>().map_err(|_| "Shouldn't happen.").unwrap().0);
549
550 let rc: $crate::__alloc::rc::Rc<$base_type> = $crate::__alloc::rc::Rc::new(Foo(42));
552 let res = rc.downcast_rc::<Bar>();
553 assert!(res.is_err());
554 let rc = res.unwrap_err();
555 assert_eq!(
557 42, rc.downcast_rc::<Foo>().map_err(|_| "Shouldn't happen.").unwrap().0);
558
559 $($more_tests)*
560 }
561 };
562 (
563 $test_mod_name:ident,
564 trait $base_trait:path { $($base_impl:tt)* },
565 non_sync: { $($non_sync_def:tt)+ },
566 sync: { $($sync_def:tt)+ }
567 ) => {
568 test_mod! {
569 $test_mod_name,
570 trait $base_trait { $($base_impl:tt)* },
571 type $base_trait,
572 non_sync: { $($non_sync_def)* },
573 sync: { $($sync_def)* }
574 }
575 };
576
577 }
578
579 test_mod!(non_generic, trait Base {},
580 non_sync: {
581 trait Base: Downcast {}
582 impl_downcast!(Base);
583 },
584 sync: {
585 trait Base: DowncastSync {}
586 impl_downcast!(sync Base);
587 });
588
589 test_mod!(generic, trait Base<u32> {},
590 non_sync: {
591 trait Base<T>: Downcast {}
592 impl_downcast!(Base<T>);
593 },
594 sync: {
595 trait Base<T>: DowncastSync {}
596 impl_downcast!(sync Base<T>);
597 });
598
599 test_mod!(constrained_generic, trait Base<u32> {},
600 non_sync: {
601 trait Base<T: Copy>: Downcast {}
602 impl_downcast!(Base<T> where T: Copy);
603 },
604 sync: {
605 trait Base<T: Copy>: DowncastSync {}
606 impl_downcast!(sync Base<T> where T: Copy);
607 });
608
609 test_mod!(associated,
610 trait Base { type H = f32; },
611 type dyn Base<H=f32>,
612 non_sync: {
613 trait Base: Downcast { type H; }
614 impl_downcast!(Base assoc H);
615 },
616 sync: {
617 trait Base: DowncastSync { type H; }
618 impl_downcast!(sync Base assoc H);
619 });
620
621 test_mod!(constrained_associated,
622 trait Base { type H = f32; },
623 type dyn Base<H=f32>,
624 non_sync: {
625 trait Base: Downcast { type H: Copy; }
626 impl_downcast!(Base assoc H where H: Copy);
627 },
628 sync: {
629 trait Base: DowncastSync { type H: Copy; }
630 impl_downcast!(sync Base assoc H where H: Copy);
631 });
632
633 test_mod!(param_and_associated,
634 trait Base<u32> { type H = f32; },
635 type dyn Base<u32, H=f32>,
636 non_sync: {
637 trait Base<T>: Downcast { type H; }
638 impl_downcast!(Base<T> assoc H);
639 },
640 sync: {
641 trait Base<T>: DowncastSync { type H; }
642 impl_downcast!(sync Base<T> assoc H);
643 });
644
645 test_mod!(constrained_param_and_associated,
646 trait Base<u32> { type H = f32; },
647 type dyn Base<u32, H=f32>,
648 non_sync: {
649 trait Base<T: Clone>: Downcast { type H: Copy; }
650 impl_downcast!(Base<T> assoc H where T: Clone, H: Copy);
651 },
652 sync: {
653 trait Base<T: Clone>: DowncastSync { type H: Copy; }
654 impl_downcast!(sync Base<T> assoc H where T: Clone, H: Copy);
655 });
656
657 test_mod!(concrete_parametrized, trait Base<u32> {},
658 non_sync: {
659 trait Base<T>: Downcast {}
660 impl_downcast!(concrete Base<u32>);
661 },
662 sync: {
663 trait Base<T>: DowncastSync {}
664 impl_downcast!(sync concrete Base<u32>);
665 });
666
667 test_mod!(concrete_associated,
668 trait Base { type H = u32; },
669 type dyn Base<H=u32>,
670 non_sync: {
671 trait Base: Downcast { type H; }
672 impl_downcast!(concrete Base assoc H=u32);
673 },
674 sync: {
675 trait Base: DowncastSync { type H; }
676 impl_downcast!(sync concrete Base assoc H=u32);
677 });
678
679 test_mod!(concrete_parametrized_associated,
680 trait Base<u32> { type H = f32; },
681 type dyn Base<u32, H=f32>,
682 non_sync: {
683 trait Base<T>: Downcast { type H; }
684 impl_downcast!(concrete Base<u32> assoc H=f32);
685 },
686 sync: {
687 trait Base<T>: DowncastSync { type H; }
688 impl_downcast!(sync concrete Base<u32> assoc H=f32);
689 });
690}