rocketmq_rust/
arc_mut.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#![allow(dead_code)]
19
20use core::fmt;
21use std::cell::SyncUnsafeCell;
22use std::fmt::Debug;
23use std::fmt::Formatter;
24use std::hash::Hash;
25use std::hash::Hasher;
26use std::ops::Deref;
27use std::ops::DerefMut;
28use std::sync::Arc;
29use std::sync::Weak;
30
31pub struct WeakArcMut<T: ?Sized> {
32    inner: Weak<SyncUnsafeCell<T>>,
33}
34
35// Implementation of PartialEq for WeakArcMut<T>
36impl<T: PartialEq + ?Sized> PartialEq for WeakArcMut<T> {
37    fn eq(&self, other: &Self) -> bool {
38        if let (Some(a), Some(b)) = (self.inner.upgrade(), other.inner.upgrade()) {
39            unsafe { *a.get() == *b.get() }
40        } else {
41            false
42        }
43    }
44}
45
46// Implementation of Eq for WeakArcMut<T>
47impl<T: Eq + ?Sized> Eq for WeakArcMut<T> {}
48
49// Implementation of Hash for WeakArcMut<T>
50
51impl<T: Hash + ?Sized> Hash for WeakArcMut<T> {
52    fn hash<H: Hasher>(&self, state: &mut H) {
53        if let Some(arc) = self.inner.upgrade() {
54            unsafe { (*arc.get()).hash(state) }
55        }
56    }
57}
58
59impl<T: ?Sized> Clone for WeakArcMut<T> {
60    fn clone(&self) -> Self {
61        Self {
62            inner: self.inner.clone(),
63        }
64    }
65}
66
67impl<T: ?Sized> WeakArcMut<T> {
68    #[inline]
69    pub fn upgrade(&self) -> Option<ArcMut<T>> {
70        self.inner.upgrade().map(|inner| ArcMut { inner })
71    }
72}
73
74#[derive(Default)]
75pub struct ArcMut<T: ?Sized> {
76    inner: Arc<SyncUnsafeCell<T>>,
77}
78
79// Implementation of PartialEq for ArcMut<T>
80impl<T: PartialEq + ?Sized> PartialEq for ArcMut<T> {
81    fn eq(&self, other: &Self) -> bool {
82        unsafe { *self.inner.get() == *other.inner.get() }
83    }
84}
85
86impl<T: Eq + ?Sized> Eq for ArcMut<T> {}
87
88impl<T: Hash> Hash for ArcMut<T> {
89    #[inline]
90    fn hash<H: Hasher>(&self, state: &mut H) {
91        // Compute the hash of the inner value
92        unsafe { (*self.inner.get()).hash(state) }
93    }
94}
95
96impl<T> ArcMut<T> {
97    #[inline]
98    pub fn new(value: T) -> Self {
99        Self {
100            inner: Arc::new(SyncUnsafeCell::new(value)),
101        }
102    }
103
104    #[inline]
105    #[allow(clippy::mut_from_ref)]
106    pub fn mut_from_ref(&self) -> &mut T {
107        unsafe { &mut *self.inner.get() }
108    }
109
110    #[inline]
111    pub fn downgrade(this: &Self) -> WeakArcMut<T> {
112        WeakArcMut {
113            inner: Arc::downgrade(&this.inner),
114        }
115    }
116
117    #[inline]
118    pub fn get_inner(&self) -> &Arc<SyncUnsafeCell<T>> {
119        &self.inner
120    }
121
122    pub fn try_unwrap(self) -> Result<T, Self> {
123        match Arc::try_unwrap(self.inner) {
124            Ok(cell) => Ok(cell.into_inner()),
125            Err(inner) => Err(Self { inner }),
126        }
127    }
128
129    pub fn strong_count(&self) -> usize {
130        Arc::strong_count(&self.inner)
131    }
132
133    pub fn weak_count(&self) -> usize {
134        Arc::weak_count(&self.inner)
135    }
136}
137
138impl<T: ?Sized> Clone for ArcMut<T> {
139    #[inline]
140    fn clone(&self) -> Self {
141        ArcMut {
142            inner: Arc::clone(&self.inner),
143        }
144    }
145}
146
147impl<T: ?Sized> AsRef<T> for ArcMut<T> {
148    #[inline]
149    fn as_ref(&self) -> &T {
150        unsafe { &*self.inner.get() }
151    }
152}
153
154impl<T: ?Sized> AsMut<T> for ArcMut<T> {
155    #[inline]
156    fn as_mut(&mut self) -> &mut T {
157        unsafe { &mut *self.inner.get() }
158    }
159}
160
161impl<T: ?Sized> Deref for ArcMut<T> {
162    type Target = T;
163
164    #[inline]
165    fn deref(&self) -> &Self::Target {
166        self.as_ref()
167    }
168}
169
170impl<T: ?Sized> DerefMut for ArcMut<T> {
171    #[inline]
172    fn deref_mut(&mut self) -> &mut Self::Target {
173        self.as_mut()
174    }
175}
176
177pub struct SyncUnsafeCellWrapper<T: ?Sized> {
178    inner: SyncUnsafeCell<T>,
179}
180
181impl<T> SyncUnsafeCellWrapper<T> {
182    #[inline]
183    pub fn new(value: T) -> Self {
184        Self {
185            inner: SyncUnsafeCell::new(value),
186        }
187    }
188}
189
190impl<T> SyncUnsafeCellWrapper<T> {
191    #[inline]
192    #[allow(clippy::mut_from_ref)]
193    pub fn mut_from_ref(&self) -> &mut T {
194        unsafe { &mut *self.inner.get() }
195    }
196}
197
198impl<T> AsRef<T> for SyncUnsafeCellWrapper<T> {
199    #[inline]
200    fn as_ref(&self) -> &T {
201        unsafe { &*self.inner.get() }
202    }
203}
204
205impl<T> AsMut<T> for SyncUnsafeCellWrapper<T> {
206    #[inline]
207    fn as_mut(&mut self) -> &mut T {
208        &mut *self.inner.get_mut()
209    }
210}
211
212impl<T> Deref for SyncUnsafeCellWrapper<T> {
213    type Target = T;
214
215    #[inline]
216    fn deref(&self) -> &Self::Target {
217        self.as_ref()
218    }
219}
220
221impl<T> DerefMut for SyncUnsafeCellWrapper<T> {
222    #[inline]
223    fn deref_mut(&mut self) -> &mut Self::Target {
224        self.as_mut()
225    }
226}
227
228impl<T: ?Sized + Debug> std::fmt::Debug for ArcMut<T> {
229    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
230        fmt::Debug::fmt(&**self, f)
231    }
232}
233
234#[cfg(test)]
235mod arc_cell_wrapper_tests {
236    use std::sync::Arc;
237
238    use super::*;
239
240    #[test]
241    fn new_creates_arc_cell_wrapper_with_provided_value() {
242        let wrapper = ArcMut::new(10);
243        assert_eq!(*wrapper.as_ref(), 10);
244    }
245
246    #[test]
247    fn clone_creates_a_new_instance_with_same_value() {
248        let wrapper = ArcMut::new(20);
249        let cloned_wrapper = wrapper.clone();
250        assert_eq!(*cloned_wrapper.as_ref(), 20);
251    }
252
253    #[test]
254    fn as_ref_returns_immutable_reference_to_value() {
255        let wrapper = ArcMut::new(30);
256        assert_eq!(*wrapper.as_ref(), 30);
257    }
258
259    #[test]
260    fn as_mut_returns_mutable_reference_to_value() {
261        let mut wrapper = ArcMut::new(40);
262        *wrapper.as_mut() = 50;
263        assert_eq!(*wrapper.as_ref(), 50);
264    }
265
266    #[test]
267    fn deref_returns_reference_to_inner_value() {
268        let wrapper = ArcMut::new(60);
269        assert_eq!(*wrapper, 60);
270    }
271
272    #[test]
273    fn deref_mut_allows_modification_of_inner_value() {
274        let mut wrapper = ArcMut::new(70);
275        *wrapper = 80;
276        assert_eq!(*wrapper, 80);
277    }
278
279    #[test]
280    fn multiple_clones_share_the_same_underlying_data() {
281        let wrapper = ArcMut::new(Arc::new(90));
282        let cloned_wrapper1 = wrapper.clone();
283        let cloned_wrapper2 = wrapper.clone();
284
285        assert_eq!(Arc::strong_count(wrapper.as_ref()), 1);
286        assert_eq!(Arc::strong_count(cloned_wrapper1.as_ref()), 1);
287        assert_eq!(Arc::strong_count(cloned_wrapper2.as_ref()), 1);
288    }
289}