Skip to content

Commit 9697076

Browse files
committed
Implement arc::Weak::new()
1 parent 4741ad3 commit 9697076

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/liballoc/arc.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ use core::cmp::Ordering;
7979
use core::mem::{align_of_val, size_of_val};
8080
use core::intrinsics::abort;
8181
use core::mem;
82+
use core::mem::uninitialized;
8283
use core::ops::Deref;
8384
#[cfg(not(stage0))]
8485
use core::ops::CoerceUnsized;
@@ -910,6 +911,36 @@ impl<T> From<T> for Arc<T> {
910911
}
911912
}
912913

914+
impl<T> Weak<T> {
915+
/// Constructs a new `Weak<T>` without an accompanying instance of T.
916+
///
917+
/// This allocates memory for T, but does not initialize it. Calling
918+
/// Weak<T>::upgrade() on the return value always gives None.
919+
///
920+
/// # Examples
921+
///
922+
/// ```
923+
/// #![feature(downgraded_weak)]
924+
///
925+
/// use std::sync::Arc;
926+
///
927+
/// let five = Arc::new(5);
928+
/// ```
929+
#[unstable(feature = "downgraded_weak",
930+
reason = "recently added",
931+
issue = "30425")]
932+
pub fn new() -> Weak<T> {
933+
unsafe {
934+
let x: Box<_> = box ArcInner {
935+
strong: atomic::AtomicUsize::new(0),
936+
weak: atomic::AtomicUsize::new(1),
937+
data: uninitialized(),
938+
};
939+
Weak { _ptr: Shared::new(Box::into_raw(x)) }
940+
}
941+
}
942+
}
943+
913944
#[cfg(test)]
914945
mod tests {
915946
use std::clone::Clone;
@@ -1160,6 +1191,12 @@ mod tests {
11601191
let foo_arc = Arc::from(foo);
11611192
assert!(123 == *foo_arc);
11621193
}
1194+
1195+
#[test]
1196+
fn test_new_weak() {
1197+
let foo: Weak<usize> = Weak::new();
1198+
assert!(foo.upgrade().is_none());
1199+
}
11631200
}
11641201

11651202
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)