/rust/registry/src/index.crates.io-1949cf8c6b5b557f/fallible_collections-0.5.1/src/arc.rs
Line | Count | Source |
1 | | //! Implement a Fallible Arc |
2 | | #[cfg(not(feature = "unstable"))] |
3 | | use super::FallibleBox; |
4 | | use super::TryClone; |
5 | | use crate::TryReserveError; |
6 | | |
7 | | #[cfg(not(feature = "unstable"))] |
8 | | use alloc::boxed::Box; |
9 | | use alloc::sync::Arc; |
10 | | |
11 | | /// trait to implement Fallible Arc |
12 | | #[cfg_attr( |
13 | | not(feature = "unstable"), |
14 | | deprecated( |
15 | | since = "0.3.1", |
16 | | note = "⚠️️️this function is not completely fallible, it can panic !, see [issue](https://github.com/vcombey/fallible_collections/issues/13). help wanted" |
17 | | ) |
18 | | )] |
19 | | pub trait FallibleArc<T> { |
20 | | /// try creating a new Arc, returning a Result<Box<T>, |
21 | | /// TryReserveError> if allocation failed |
22 | | fn try_new(t: T) -> Result<Self, TryReserveError> |
23 | | where |
24 | | Self: Sized; |
25 | | } |
26 | | |
27 | | #[allow(deprecated)] |
28 | | impl<T> FallibleArc<T> for Arc<T> { |
29 | 0 | fn try_new(t: T) -> Result<Self, TryReserveError> { |
30 | | #[cfg(not(feature = "unstable"))] |
31 | | { |
32 | | // doesn't work as the inner variable of arc are also stocked in the box |
33 | 0 | let b = <Box<T> as FallibleBox<T>>::try_new(t)?; |
34 | 0 | Ok(Arc::from(b)) |
35 | | } |
36 | | #[cfg(feature = "unstable")] |
37 | | { |
38 | | use alloc::alloc::Layout; |
39 | | use alloc::collections::TryReserveErrorKind; |
40 | | Arc::try_new(t).map_err(|_e| { |
41 | | TryReserveErrorKind::AllocError { |
42 | | layout: Layout::new::<Arc<T>>(), // This is bullshit |
43 | | non_exhaustive: (), |
44 | | } |
45 | | .into() |
46 | | }) |
47 | | } |
48 | 0 | } |
49 | | } |
50 | | |
51 | | /// Just a TryClone boilerplate for Arc |
52 | | impl<T: ?Sized> TryClone for Arc<T> { |
53 | 0 | fn try_clone(&self) -> Result<Self, TryReserveError> { |
54 | 0 | Ok(self.clone()) |
55 | 0 | } |
56 | | } |
57 | | |
58 | | #[cfg(test)] |
59 | | mod test { |
60 | | #[test] |
61 | | fn fallible_rc() { |
62 | | use std::sync::Arc; |
63 | | |
64 | | let mut x = Arc::new(3); |
65 | | *Arc::get_mut(&mut x).unwrap() = 4; |
66 | | assert_eq!(*x, 4); |
67 | | |
68 | | let _y = Arc::clone(&x); |
69 | | assert!(Arc::get_mut(&mut x).is_none()); |
70 | | } |
71 | | } |