From fcc79f2d60d55114ae890e1112393ef0e2e8d93f Mon Sep 17 00:00:00 2001 From: Alexander Bulaev Date: Wed, 4 Nov 2015 15:03:33 +0300 Subject: liballoc: implement From for Box, Rc, Arc Sometimes when writing generic code you want to abstract over owning/pointer type so that calling code isn't restricted by one concrete owning/pointer type. This commit makes possible such code: ``` fn i_will_work_with_arc>>(t: T) { let the_arc = t.into(); // Do something } i_will_work_with_arc(MyTy::new()); i_will_work_with_arc(Box::new(MyTy::new())); let arc_that_i_already_have = Arc::new(MyTy::new()); i_will_work_with_arc(arc_that_i_already_have); ``` Please note that this patch doesn't work with DSTs. --- src/liballoc/arc.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'src/liballoc/arc.rs') diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 95dcdd22fd0..36f915d19e9 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -84,6 +84,7 @@ use core::ptr::{self, Shared}; use core::marker::Unsize; use core::hash::{Hash, Hasher}; use core::{usize, isize}; +use core::convert::From; use heap::deallocate; const MAX_REFCOUNT: usize = (isize::MAX) as usize; @@ -894,8 +895,23 @@ impl Hash for Arc { } } +#[stable(feature = "rust1", since = "1.6.0")] +impl From for Arc { + fn from(t: T) -> Self { + Arc::new(t) + } +} + +#[stable(feature = "rust1", since = "1.6.0")] +impl From> for Arc { + fn from(t: Box) -> Self { + Arc::new(*t) + } +} + #[cfg(test)] mod tests { + use std::boxed::Box; use std::clone::Clone; use std::sync::mpsc::channel; use std::mem::drop; @@ -908,6 +924,7 @@ mod tests { use std::vec::Vec; use super::{Arc, Weak}; use std::sync::Mutex; + use std::convert::From; struct Canary(*mut atomic::AtomicUsize); @@ -1137,6 +1154,20 @@ mod tests { drop(x); assert!(y.upgrade().is_none()); } + + #[test] + fn test_from_owned() { + let foo = 123; + let foo_arc = Arc::from(foo); + assert!(123 == *foo_arc); + } + + #[test] + fn test_from_box() { + let foo_box = Box::new(123); + let foo_arc = Arc::from(foo_box); + assert!(123 == *foo_arc); + } } impl borrow::Borrow for Arc { -- cgit 1.4.1-3-g733a5