From 550373b1f9d59a4ce5cd61cb1bca2488c0ec6471 Mon Sep 17 00:00:00 2001 From: Clar Charr Date: Tue, 31 Jan 2017 22:46:16 -0500 Subject: [PATCH] Direct conversions between slices and boxes. --- src/liballoc/boxed.rs | 17 +++++++++++++++++ src/liballoc/boxed_test.rs | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 82d361fb0e8..ac9439974a4 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -419,6 +419,23 @@ impl From for Box { } } +#[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 { + fn from(s: &'a str) -> Box { + let boxed: Box<[u8]> = Box::from(s.as_bytes()); + unsafe { mem::transmute(boxed) } + } +} + impl Box { #[inline] #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/liballoc/boxed_test.rs b/src/liballoc/boxed_test.rs index 8d68ce3c1f6..837f8dfaca1 100644 --- a/src/liballoc/boxed_test.rs +++ b/src/liballoc/boxed_test.rs @@ -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; @@ -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 = Box::from(s); + assert_eq!(&*boxed, s) +}