Skip to content

Commit 550373b

Browse files
author
Clar Charr
committed
Direct conversions between slices and boxes.
1 parent 031c116 commit 550373b

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/liballoc/boxed.rs

+17
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,23 @@ impl<T> From<T> for Box<T> {
419419
}
420420
}
421421

422+
#[stable(feature = "box_from_slice", since = "1.17.0")]
423+
impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
424+
fn from(slice: &'a [T]) -> Box<[T]> {
425+
let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
426+
boxed.copy_from_slice(slice);
427+
boxed
428+
}
429+
}
430+
431+
#[stable(feature = "box_from_slice", since = "1.17.0")]
432+
impl<'a> From<&'a str> for Box<str> {
433+
fn from(s: &'a str) -> Box<str> {
434+
let boxed: Box<[u8]> = Box::from(s.as_bytes());
435+
unsafe { mem::transmute(boxed) }
436+
}
437+
}
438+
422439
impl Box<Any> {
423440
#[inline]
424441
#[stable(feature = "rust1", since = "1.0.0")]

src/liballoc/boxed_test.rs

+23
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ use core::any::Any;
1414
use core::ops::Deref;
1515
use core::result::Result::{Err, Ok};
1616
use core::clone::Clone;
17+
use core::f64;
18+
use core::i64;
1719

1820
use std::boxed::Box;
1921

@@ -117,3 +119,24 @@ fn raw_trait() {
117119
assert_eq!(19, y.get());
118120
}
119121
}
122+
123+
#[test]
124+
fn f64_slice() {
125+
let slice: &[f64] = &[-1.0, 0.0, 1.0, f64::INFINITY];
126+
let boxed: Box<[f64]> = Box::from(slice);
127+
assert_eq!(&*boxed, slice)
128+
}
129+
130+
#[test]
131+
fn i64_slice() {
132+
let slice: &[i64] = &[i64::MIN, -2, -1, 0, 1, 2, i64::MAX];
133+
let boxed: Box<[i64]> = Box::from(slice);
134+
assert_eq!(&*boxed, slice)
135+
}
136+
137+
#[test]
138+
fn str_slice() {
139+
let s = "Hello, world!";
140+
let boxed: Box<str> = Box::from(s);
141+
assert_eq!(&*boxed, s)
142+
}

0 commit comments

Comments
 (0)