Debian Codegraph @

debian/missing-sources/fallible_collections/src/arc.rs

raw
1 //! Implement a Fallible Arc
2 #[cfg(any(not(feature = "unstable"), feature = "rust_1_57"))]
3 use super::FallibleBox;
4 use super::TryClone;
5 use crate::TryReserveError;
6
7 #[cfg(any(not(feature = "unstable"), feature = "rust_1_57"))]
8 use alloc::boxed::Box;
9 use alloc::sync::Arc;
10
11 /// trait to implement Fallible Arc
12 #[cfg_attr(
13 any(not(feature = "unstable"), feature = "rust_1_57"),
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 fn try_new(t: T) -> Result<Self, TryReserveError> {
30 #[cfg(any(not(feature = "unstable"), feature = "rust_1_57"))]
31 {
32 // doesn't work as the inner variable of arc are also stocked in the box
33 let b = <Box<T> as FallibleBox<T>>::try_new(t)?;
34 Ok(Arc::from(b))
35 }
36 #[cfg(all(feature = "unstable", not(feature = "rust_1_57")))]
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 }
49 }
50
51 /// Just a TryClone boilerplate for Arc
52 impl<T: ?Sized> TryClone for Arc<T> {
53 fn try_clone(&self) -> Result<Self, TryReserveError> {
54 Ok(self.clone())
55 }
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 }