From db76ac73309332927d04e4f8bf5d235dc6f32360 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 16 Sep 2015 23:17:39 -0700 Subject: [PATCH] std: Add AsRef/AsMut impls to Box/Rc/Arc These common traits were left off originally by accident from these smart pointers, and a past attempt (#26008) to add them was later reverted (#26160) due to unexpected breakge (#26096) occurring. The specific breakage in worry is the meaning of this return value changed: let a: Box> = ...; a.as_ref() Currently this returns `Option<&T>` but after this change it will return `&Option` because the `AsRef::as_ref` method shares the same name as `Option::as_ref`. A [crater report][crater] of this change, however, has shown that the fallout of this change is quite minimal. These trait implementations are "the right impls to add" to these smart pointers and would enable various generalizations such as those in #27197. [crater]: https://gist.github.com/anonymous/0ba4c3512b07641c0f99 This commit is a breaking change for the above reasons mentioned, and the mitigation strategies look like any of: Option::as_ref(&a) a.as_ref().as_ref() (*a).as_ref() --- src/liballoc/arc.rs | 5 +++++ src/liballoc/boxed.rs | 10 ++++++++++ src/liballoc/rc.rs | 5 +++++ 3 files changed, 20 insertions(+) diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index ceca44fc1ac29..f66f1f13dcb23 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -1148,3 +1148,8 @@ impl borrow::Borrow for Arc { &**self } } + +#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] +impl AsRef for Arc { + fn as_ref(&self) -> &T { &**self } +} diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 1529187da064c..629adf4649d38 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -594,3 +594,13 @@ impl borrow::BorrowMut for Box { &mut **self } } + +#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] +impl AsRef for Box { + fn as_ref(&self) -> &T { &**self } +} + +#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] +impl AsMut for Box { + fn as_mut(&mut self) -> &mut T { &mut **self } +} diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 3507f123a6f15..2f0bf1281b344 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -1117,3 +1117,8 @@ impl borrow::Borrow for Rc { &**self } } + +#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] +impl AsRef for Rc { + fn as_ref(&self) -> &T { &**self } +}