Skip to content

Commit

Permalink
Add implementations for Any + Send + Sync
Browse files Browse the repository at this point in the history
Implement `is`, `downcast_ref`, `downcast_mut` and `Debug` for
`Any + Send + Sync`.
  • Loading branch information
jsgf committed May 31, 2018
1 parent 5342d40 commit 72433e1
Showing 1 changed file with 90 additions and 0 deletions.
90 changes: 90 additions & 0 deletions src/libcore/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,13 @@ impl fmt::Debug for Any + Send {
}
}

#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
impl fmt::Debug for Any + Send + Sync {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Any")
}
}

impl Any {
/// Returns `true` if the boxed type is the same as `T`.
///
Expand Down Expand Up @@ -325,6 +332,89 @@ impl Any+Send {
}
}

impl Any+Send+Sync {
/// Forwards to the method defined on the type `Any`.
///
/// # Examples
///
/// ```
/// use std::any::Any;
///
/// fn is_string(s: &(Any + Send + Sync)) {
/// if s.is::<String>() {
/// println!("It's a string!");
/// } else {
/// println!("Not a string...");
/// }
/// }
///
/// fn main() {
/// is_string(&0);
/// is_string(&"cookie monster".to_string());
/// }
/// ```
#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
#[inline]
pub fn is<T: Any>(&self) -> bool {
Any::is::<T>(self)
}

/// Forwards to the method defined on the type `Any`.
///
/// # Examples
///
/// ```
/// use std::any::Any;
///
/// fn print_if_string(s: &(Any + Send)) {
/// if let Some(string) = s.downcast_ref::<String>() {
/// println!("It's a string({}): '{}'", string.len(), string);
/// } else {
/// println!("Not a string...");
/// }
/// }
///
/// fn main() {
/// print_if_string(&0);
/// print_if_string(&"cookie monster".to_string());
/// }
/// ```
#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
Any::downcast_ref::<T>(self)
}

/// Forwards to the method defined on the type `Any`.
///
/// # Examples
///
/// ```
/// use std::any::Any;
///
/// fn modify_if_u32(s: &mut (Any+ Send)) {
/// if let Some(num) = s.downcast_mut::<u32>() {
/// *num = 42;
/// }
/// }
///
/// fn main() {
/// let mut x = 10u32;
/// let mut s = "starlord".to_string();
///
/// modify_if_u32(&mut x);
/// modify_if_u32(&mut s);
///
/// assert_eq!(x, 42);
/// assert_eq!(&s, "starlord");
/// }
/// ```
#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
Any::downcast_mut::<T>(self)
}
}

///////////////////////////////////////////////////////////////////////////////
// TypeID and its methods
Expand Down

0 comments on commit 72433e1

Please sign in to comment.