@@ -39,6 +39,83 @@ use core::{
39
39
///
40
40
/// The reference count on an instance of [`Arc`] is always non-zero.
41
41
/// The object pointed to by [`Arc`] is always pinned.
42
+ ///
43
+ /// # Examples
44
+ ///
45
+ /// ```
46
+ /// use kernel::sync::Arc;
47
+ ///
48
+ /// struct Example {
49
+ /// a: u32,
50
+ /// b: u32,
51
+ /// }
52
+ ///
53
+ /// // Create a ref-counted instance of `Example`.
54
+ /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
55
+ ///
56
+ /// // Get a new pointer to `obj` and increment the refcount.
57
+ /// let cloned = obj.clone();
58
+ ///
59
+ /// // Assert that both `obj` and `cloned` point to the same underlying object.
60
+ /// assert!(core::ptr::eq(&*obj, &*cloned));
61
+ ///
62
+ /// // Destroy `obj` and decrement its refcount.
63
+ /// drop(obj);
64
+ ///
65
+ /// // Check that the values are still accessible through `cloned`.
66
+ /// assert_eq!(cloned.a, 10);
67
+ /// assert_eq!(cloned.b, 20);
68
+ ///
69
+ /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
70
+ /// ```
71
+ ///
72
+ /// Using `Arc<T>` as the type of `self`:
73
+ ///
74
+ /// ```
75
+ /// use kernel::sync::Arc;
76
+ ///
77
+ /// struct Example {
78
+ /// a: u32,
79
+ /// b: u32,
80
+ /// }
81
+ ///
82
+ /// impl Example {
83
+ /// fn take_over(self: Arc<Self>) {
84
+ /// // ...
85
+ /// }
86
+ ///
87
+ /// fn use_reference(self: &Arc<Self>) {
88
+ /// // ...
89
+ /// }
90
+ /// }
91
+ ///
92
+ /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
93
+ /// obj.use_reference();
94
+ /// obj.take_over();
95
+ /// ```
96
+ ///
97
+ /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`:
98
+ ///
99
+ /// ```
100
+ /// use kernel::sync::{Arc, ArcBorrow};
101
+ ///
102
+ /// trait MyTrait {
103
+ /// // Trait has a function whose `self` type is `Arc<Self>`.
104
+ /// fn example1(self: Arc<Self>) {}
105
+ ///
106
+ /// // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`.
107
+ /// fn example2(self: ArcBorrow<'_, Self>) {}
108
+ /// }
109
+ ///
110
+ /// struct Example;
111
+ /// impl MyTrait for Example {}
112
+ ///
113
+ /// // `obj` has type `Arc<Example>`.
114
+ /// let obj: Arc<Example> = Arc::try_new(Example)?;
115
+ ///
116
+ /// // `coerced` has type `Arc<dyn MyTrait>`.
117
+ /// let coerced: Arc<dyn MyTrait> = obj;
118
+ /// ```
42
119
pub struct Arc < T : ?Sized > {
43
120
ptr : NonNull < ArcInner < T > > ,
44
121
_p : PhantomData < ArcInner < T > > ,
0 commit comments