From 1ca77268d97b62e2fcaa1642aaf9313e164963b3 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 12 Dec 2013 17:36:30 -0800 Subject: [PATCH] std: Change Any::move to never consume the object If the dynamic cast fails, this now returns the ~Any instance back to the caller. --- src/libstd/any.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/libstd/any.rs b/src/libstd/any.rs index 8bce687e245..49bae30a461 100644 --- a/src/libstd/any.rs +++ b/src/libstd/any.rs @@ -20,10 +20,11 @@ use cast::transmute; use option::{Option, Some, None}; +use result::{Result, Ok, Err}; use to_str::ToStr; +use unstable::intrinsics::TypeId; use unstable::intrinsics; use util::Void; -use unstable::intrinsics::TypeId; /////////////////////////////////////////////////////////////////////////////// // Any trait @@ -119,12 +120,12 @@ impl<'a> AnyMutRefExt<'a> for &'a mut Any { pub trait AnyOwnExt { /// Returns the boxed value if it is of type `T`, or /// `None` if it isn't. - fn move(self) -> Option<~T>; + fn move(self) -> Result<~T, Self>; } impl AnyOwnExt for ~Any { #[inline] - fn move(self) -> Option<~T> { + fn move(self) -> Result<~T, ~Any> { if self.is::() { unsafe { // Extract the pointer to the boxed value, temporary alias with self @@ -133,10 +134,10 @@ impl AnyOwnExt for ~Any { // Prevent destructor on self being run intrinsics::forget(self); - Some(ptr) + Ok(ptr) } } else { - None + Err(self) } } } @@ -384,13 +385,13 @@ mod tests { let a = ~8u as ~Any; let b = ~Test as ~Any; - assert_eq!(a.move(), Some(~8u)); - assert_eq!(b.move(), Some(~Test)); + assert_eq!(a.move(), Ok(~8u)); + assert_eq!(b.move(), Ok(~Test)); let a = ~8u as ~Any; let b = ~Test as ~Any; - assert_eq!(a.move(), None::<~Test>); - assert_eq!(b.move(), None::<~uint>); + assert!(a.move::<~Test>().is_err()); + assert!(b.move::<~uint>().is_err()); } }