| 1 |
//! Implement a Fallible Rc |
| 2 |
use super::FallibleBox; |
| 3 |
use crate::TryReserveError; |
| 4 |
use alloc::boxed::Box; |
| 5 |
use alloc::rc::Rc; |
| 6 |
/// trait to implement Fallible Rc |
| 7 |
pub trait FallibleRc<T> { |
| 8 |
/// try creating a new Rc, returning a Result<Box<T>, |
| 9 |
/// TryReserveError> if allocation failed |
| 10 |
fn try_new(t: T) -> Result<Self, TryReserveError> |
| 11 |
where |
| 12 |
Self: Sized; |
| 13 |
} |
| 14 |
|
| 15 |
impl<T> FallibleRc<T> for Rc<T> { |
| 16 |
fn try_new(t: T) -> Result<Self, TryReserveError> { |
| 17 |
let b = <Box<T> as FallibleBox<T>>::try_new(t)?; |
| 18 |
Ok(Rc::from(b)) |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
#[cfg(test)] |
| 23 |
mod test { |
| 24 |
#[test] |
| 25 |
fn fallible_rc() { |
| 26 |
use std::rc::Rc; |
| 27 |
|
| 28 |
let mut x = Rc::new(3); |
| 29 |
*Rc::get_mut(&mut x).unwrap() = 4; |
| 30 |
assert_eq!(*x, 4); |
| 31 |
|
| 32 |
let _y = Rc::clone(&x); |
| 33 |
assert!(Rc::get_mut(&mut x).is_none()); |
| 34 |
} |
| 35 |
} |