diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 2b3a18a439fc9..762ae2cfde6a4 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -1277,6 +1277,7 @@ impl From for Box { /// from the stack into it. /// /// # Examples + /// /// ```rust /// let x = 5; /// let boxed = Box::new(5); @@ -1330,6 +1331,10 @@ impl From<&[T]> for Box<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "box_from_cow", since = "1.45.0")] impl From> for Box<[T]> { + /// Converts a `Cow<'_, [T]>` into a `Box<[T]>` + /// + /// This conversion allocates on the heap + /// and performs a copy of `s`. #[inline] fn from(cow: Cow<'_, [T]>) -> Box<[T]> { match cow { @@ -1348,6 +1353,7 @@ impl From<&str> for Box { /// and performs a copy of `s`. /// /// # Examples + /// /// ```rust /// let boxed: Box = Box::from("hello"); /// println!("{}", boxed); @@ -1361,6 +1367,24 @@ impl From<&str> for Box { #[cfg(not(no_global_oom_handling))] #[stable(feature = "box_from_cow", since = "1.45.0")] impl From> for Box { + /// Converts a `Cow<'_, str>` into a `Box` + /// + /// This conversion allocates on the heap + /// and performs a copy of `cow`. + /// + /// # Examples + /// + /// ```rust + /// let unboxed = Cow::Borrowed("hello"); + /// let boxed: Box = Box::from(unboxed); + /// println!("{}", boxed); + /// ``` + /// + /// ```rust + /// let unboxed = Cow::Owned("hello".to_string()); + /// let boxed: Box = Box::from(unboxed); + /// println!("{}", boxed); + /// ``` #[inline] fn from(cow: Cow<'_, str>) -> Box { match cow { @@ -1403,6 +1427,7 @@ impl From<[T; N]> for Box<[T]> { /// This conversion moves the array to newly heap-allocated memory. /// /// # Examples + /// /// ```rust /// let boxed: Box<[u8]> = Box::from([4, 2]); /// println!("{:?}", boxed); @@ -1416,6 +1441,14 @@ impl From<[T; N]> for Box<[T]> { impl TryFrom> for Box<[T; N]> { type Error = Box<[T]>; + /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`. + /// + /// The conversion occurs in-place and does not require a + /// new memory allocation. + /// + /// # Errors + /// + /// Returns an error if `boxed_slice.len()` does not equal `N`. fn try_from(boxed_slice: Box<[T]>) -> Result { if boxed_slice.len() == N { Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })