Skip to content

Commit

Permalink
Rollup merge of rust-lang#34740 - GuillaumeGomez:boxed_doc, r=stevekl…
Browse files Browse the repository at this point in the history
…abnik

Improve boxed docs

Fixes rust-lang#29343.

r? @steveklabnik
  • Loading branch information
GuillaumeGomez authored Jul 12, 2016
2 parents a94e4c0 + 1ef7bdc commit f02754a
Showing 1 changed file with 46 additions and 3 deletions.
49 changes: 46 additions & 3 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,14 @@ impl<T: ?Sized> Box<T> {
/// This function is unsafe because improper use may lead to
/// memory problems. For example, a double-free may occur if the
/// function is called twice on the same raw pointer.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let ptr = Box::into_raw(x);
/// let x = unsafe { Box::from_raw(ptr) };
/// ```
#[stable(feature = "box_raw", since = "1.4.0")]
#[inline]
pub unsafe fn from_raw(raw: *mut T) -> Self {
Expand All @@ -266,9 +274,8 @@ impl<T: ?Sized> Box<T> {
/// # Examples
///
/// ```
/// let seventeen = Box::new(17);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// let x = Box::new(5);
/// let ptr = Box::into_raw(x);
/// ```
#[stable(feature = "box_raw", since = "1.4.0")]
#[inline]
Expand Down Expand Up @@ -399,6 +406,24 @@ impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
///
/// # Examples
///
/// ```
/// use std::any::Any;
///
/// fn print_if_string(value: Box<Any>) {
/// if let Ok(string) = value.downcast::<String>() {
/// println!("String ({}): {}", string.len(), string);
/// }
/// }
///
/// fn main() {
/// let my_string = "Hello World".to_string();
/// print_if_string(Box::new(my_string));
/// print_if_string(Box::new(0i8));
/// }
/// ```
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
Expand All @@ -419,6 +444,24 @@ impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
///
/// # Examples
///
/// ```
/// use std::any::Any;
///
/// fn print_if_string(value: Box<Any + Send>) {
/// if let Ok(string) = value.downcast::<String>() {
/// println!("String ({}): {}", string.len(), string);
/// }
/// }
///
/// fn main() {
/// let my_string = "Hello World".to_string();
/// print_if_string(Box::new(my_string));
/// print_if_string(Box::new(0i8));
/// }
/// ```
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
Expand Down

0 comments on commit f02754a

Please sign in to comment.