Skip to content

Commit

Permalink
Auto merge of #39438 - clarcharr:box_from, r=alexcrichton
Browse files Browse the repository at this point in the history
Conversions between slices and boxes

This allows conversion for `Copy` slices, `str`, and `CStr` into their boxed counterparts.

This also adds the method `CString::into_boxed_c_str`.

I would like to add similar implementations for `OsStr` as well, but I have not figured out how.
  • Loading branch information
bors committed Feb 10, 2017
2 parents bc524d3 + 550373b commit 2425b22
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,23 @@ impl<T> From<T> for Box<T> {
}
}

#[stable(feature = "box_from_slice", since = "1.17.0")]
impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
fn from(slice: &'a [T]) -> Box<[T]> {
let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
boxed.copy_from_slice(slice);
boxed
}
}

#[stable(feature = "box_from_slice", since = "1.17.0")]
impl<'a> From<&'a str> for Box<str> {
fn from(s: &'a str) -> Box<str> {
let boxed: Box<[u8]> = Box::from(s.as_bytes());
unsafe { mem::transmute(boxed) }
}
}

impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
23 changes: 23 additions & 0 deletions src/liballoc/boxed_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use core::any::Any;
use core::ops::Deref;
use core::result::Result::{Err, Ok};
use core::clone::Clone;
use core::f64;
use core::i64;

use std::boxed::Box;

Expand Down Expand Up @@ -117,3 +119,24 @@ fn raw_trait() {
assert_eq!(19, y.get());
}
}

#[test]
fn f64_slice() {
let slice: &[f64] = &[-1.0, 0.0, 1.0, f64::INFINITY];
let boxed: Box<[f64]> = Box::from(slice);
assert_eq!(&*boxed, slice)
}

#[test]
fn i64_slice() {
let slice: &[i64] = &[i64::MIN, -2, -1, 0, 1, 2, i64::MAX];
let boxed: Box<[i64]> = Box::from(slice);
assert_eq!(&*boxed, slice)
}

#[test]
fn str_slice() {
let s = "Hello, world!";
let boxed: Box<str> = Box::from(s);
assert_eq!(&*boxed, s)
}

0 comments on commit 2425b22

Please sign in to comment.