|
| 1 | +#![feature(unsize)] |
| 2 | + |
| 3 | +use std::marker::Unsize; |
| 4 | +use std::rc::Rc; |
| 5 | +use std::sync::Arc; |
| 6 | + |
| 7 | +pub trait CastTo<T: ?Sized>: Unsize<T> { |
| 8 | + fn cast_to(&self) -> &T; |
| 9 | + fn cast_mut_to(&mut self) -> &mut T; |
| 10 | + fn into_cast_to(self: Box<Self>) -> Box<T>; |
| 11 | + fn cast_rc_to(self: Rc<Self>) -> Rc<T>; |
| 12 | + fn cast_arc_to(self: Arc<Self>) -> Arc<T>; |
| 13 | +} |
| 14 | + |
| 15 | +impl<T: ?Sized> Cast for T {} |
| 16 | +pub trait Cast { |
| 17 | + fn cast<T: ?Sized>(&self) -> &T |
| 18 | + where |
| 19 | + Self: CastTo<T>, |
| 20 | + { |
| 21 | + self |
| 22 | + } |
| 23 | + |
| 24 | + fn cast_mut<T>(&mut self) -> &mut T |
| 25 | + where |
| 26 | + Self: CastTo<T>, |
| 27 | + { |
| 28 | + self.cast_mut_to() |
| 29 | + } |
| 30 | + |
| 31 | + fn into_cast<T>(self: Box<Self>) -> Box<T> |
| 32 | + where |
| 33 | + Self: CastTo<T>, |
| 34 | + { |
| 35 | + self.into_cast_to() |
| 36 | + } |
| 37 | + |
| 38 | + fn cast_rc<T>(self: Rc<Self>) -> Rc<T> |
| 39 | + where |
| 40 | + Self: CastTo<T>, |
| 41 | + { |
| 42 | + self.cast_rc_to() |
| 43 | + } |
| 44 | + |
| 45 | + fn cast_arc<T>(self: Arc<Self>) -> Arc<T> |
| 46 | + where |
| 47 | + Self: CastTo<T>, |
| 48 | + { |
| 49 | + self.cast_arc_to() |
| 50 | + } |
| 51 | +} |
| 52 | +impl<T: ?Sized, U: ?Sized + Unsize<T>> CastTo<T> for U { |
| 53 | + fn cast_to(&self) -> &T { |
| 54 | + self |
| 55 | + } |
| 56 | + |
| 57 | + fn cast_mut_to(&mut self) -> &mut T { |
| 58 | + self |
| 59 | + } |
| 60 | + |
| 61 | + fn into_cast_to(self: Box<Self>) -> Box<T> { |
| 62 | + self |
| 63 | + } |
| 64 | + |
| 65 | + fn cast_rc_to(self: Rc<Self>) -> Rc<T> { |
| 66 | + self |
| 67 | + } |
| 68 | + |
| 69 | + fn cast_arc_to(self: Arc<Self>) -> Arc<T> { |
| 70 | + self |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +pub trait Foo { |
| 75 | + fn foo(&self) { |
| 76 | + println!("Foo({})", core::any::type_name::<Self>()); |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +pub trait Bar: CastTo<dyn Foo> + CastTo<dyn core::fmt::Debug> + CastTo<[i32]> { |
| 81 | + fn bar(&self) { |
| 82 | + println!("Bar({})", core::any::type_name::<Self>()); |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +impl Foo for [i32; 10] {} |
| 87 | +impl Bar for [i32; 10] {} |
| 88 | + |
| 89 | +fn main() { |
| 90 | + let x = [0; 10]; |
| 91 | + let x: Box<dyn Bar> = Box::new(x); |
| 92 | + let x = (*x).cast::<[i32]>(); |
| 93 | + //~^ ERROR: the trait bound `dyn Bar: CastTo<[i32]>` is not satisfied |
| 94 | +} |
0 commit comments