]> git.lizzy.rs Git - rust.git/commitdiff
Direct conversions between slices and boxes.
authorClar Charr <clar@charr.xyz>
Wed, 1 Feb 2017 03:46:16 +0000 (22:46 -0500)
committerClar Charr <clar@charr.xyz>
Mon, 6 Feb 2017 23:53:13 +0000 (18:53 -0500)
src/liballoc/boxed.rs
src/liballoc/boxed_test.rs

index 82d361fb0e853064ffa317b66e582f36f87b6660..ac9439974a491c9d634c9ff461355b8b4218c6e7 100644 (file)
@@ -419,6 +419,23 @@ fn from(t: T) -> Self {
     }
 }
 
+#[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")]
index 8d68ce3c1f6e2ebfa406c81a15cb50c478df4139..837f8dfaca13a52ecddab5f7dd9b6114a8a75ae5 100644 (file)
@@ -14,6 +14,8 @@
 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 set(&mut self, value: u32) {
         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)
+}