generated from Tamschi/rust-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.rs
401 lines (364 loc) · 9.03 KB
/
sync.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
use crate::{
tip_toe_api::{AcquireOutcome, DecrementFollowup, TipToeExt},
TipToed,
};
use alloc::{
borrow::{Cow, ToOwned},
boxed::Box,
};
use core::{
any::{Any, TypeId},
borrow::Borrow,
fmt::{self, Debug, Display, Formatter, Pointer},
hash::{Hash, Hasher},
marker::PhantomData,
mem::{self, ManuallyDrop},
ops::Deref,
pin::Pin,
ptr::NonNull,
};
use tap::Pipe;
pub struct Arc<T: ?Sized + TipToed> {
pointer: NonNull<T>,
_phantom: PhantomData<T>,
}
impl<T: ?Sized + TipToed> AsRef<T> for Arc<T> {
fn as_ref(&self) -> &T {
self
}
}
impl<T: ?Sized + TipToed> Borrow<T> for Arc<T> {
fn borrow(&self) -> &T {
self
}
}
impl<T: ?Sized + TipToed> Clone for Arc<T> {
/// Makes a clone of this [`Arc`], pointing to the same instance.
///
/// This increases the strong reference count by 1.
fn clone(&self) -> Self {
self.tip_toe().increment();
Self {
pointer: self.pointer,
_phantom: PhantomData,
}
}
fn clone_from(&mut self, source: &Self) {
if !Self::ptr_eq(self, source) {
*self = source.clone()
}
}
}
impl<T: ?Sized + TipToed> Debug for Arc<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("Arc").field(&&**self).finish()
}
}
impl<T: ?Sized + TipToed> Default for Arc<T>
where
T: Default,
{
fn default() -> Self {
Self::new(T::default())
}
}
impl<T: ?Sized + TipToed> Deref for Arc<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { self.pointer.as_ref() }
}
}
impl<T: ?Sized + TipToed> Display for Arc<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
impl<T: ?Sized + TipToed> Drop for Arc<T> {
fn drop(&mut self) {
unsafe {
match self.tip_toe().decrement() {
DecrementFollowup::LeakIt => (),
DecrementFollowup::DropOrMoveIt => drop(Box::from_raw(self.pointer.as_ptr())),
}
}
}
}
impl<T: ?Sized + TipToed> Eq for Arc<T> where T: Eq {}
impl<T: ?Sized + TipToed> From<Box<T>> for Arc<T> {
/// Converts a [`Box`] into an [`Arc`] without reallocating.
fn from(box_: Box<T>) -> Self {
box_.tip_toe().increment();
unsafe { Self::from_raw(NonNull::new_unchecked(Box::leak(box_))) }
}
}
impl<'a, B: ?Sized + TipToed> From<Cow<'a, B>> for Arc<B>
where
B: ToOwned,
Arc<B>: From<B::Owned>,
{
/// Always converts into an exclusive instance,
/// either by copying or by moving the value.
fn from(cow: Cow<'a, B>) -> Self {
match cow {
Cow::Borrowed(b) => b.to_owned().into(),
Cow::Owned(o) => o.into(),
}
}
}
impl<T: Sized + TipToed> From<T> for Arc<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T: Sized + TipToed> From<T> for Pin<Arc<T>> {
fn from(value: T) -> Self {
Arc::pin(value)
}
}
impl<T: ?Sized + TipToed> From<Pin<Arc<T>>> for Arc<T>
where
T: Unpin,
{
fn from(pinned: Pin<Arc<T>>) -> Self {
Self::unpin(pinned)
}
}
impl<T: ?Sized + TipToed> From<Arc<T>> for Pin<Arc<T>> {
fn from(unpinned: Arc<T>) -> Self {
unsafe { Pin::new_unchecked(unpinned) }
}
}
impl<T: ?Sized + TipToed> Hash for Arc<T>
where
T: Hash,
{
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state)
}
}
impl<T: ?Sized + TipToed> Ord for Arc<T>
where
T: Ord,
{
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
(**self).cmp(other)
}
}
impl<T: ?Sized + TipToed, O: ?Sized + TipToed> PartialEq<Arc<O>> for Arc<T>
where
T: PartialEq<O>,
{
fn eq(&self, other: &Arc<O>) -> bool {
(**self) == (**other)
}
}
impl<T: ?Sized + TipToed, O: ?Sized + TipToed> PartialOrd<Arc<O>> for Arc<T>
where
T: PartialOrd<O>,
{
fn partial_cmp(&self, other: &Arc<O>) -> Option<core::cmp::Ordering> {
(**self).partial_cmp(other)
}
}
impl<T: ?Sized + TipToed> Pointer for Arc<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Pointer::fmt(&self.pointer, f)
}
}
unsafe impl<T: ?Sized + TipToed> Send for Arc<T> where T: Sync + Send {}
unsafe impl<T: ?Sized + TipToed> Sync for Arc<T> where T: Sync + Send {}
impl<T: ?Sized + TipToed> Unpin for Arc<T> {}
impl<T: ?Sized + TipToed> Arc<T> {
#[must_use]
pub fn new(value: T) -> Self
where
T: Sized,
{
value.tip_toe().increment();
let instance = Box::leak(Box::new(value));
unsafe { Self::from_raw(NonNull::new_unchecked(instance)) }
}
/// See also `impl From<Arc<_>> for Pin<Arc<_>>`.
#[must_use]
pub fn pin(value: T) -> Pin<Self>
where
T: Sized,
{
value.tip_toe().increment();
let instance = Box::leak(Box::new(value));
unsafe { Pin::new_unchecked(Self::from_raw(NonNull::new_unchecked(instance))) }
}
/// See also `impl From<Pin<Arc<_>>> for Arc<_>`.
#[must_use]
pub fn unpin(this: Pin<Self>) -> Self
where
T: Unpin,
{
unsafe { Pin::into_inner_unchecked(this) }
}
/// # Errors
///
/// Iff this [`Arc`] is not an exclusive handle.
pub fn try_unwrap(this: Self) -> Result<T, Self>
where
T: Sized,
{
match this.tip_toe().acquire() {
AcquireOutcome::Shared => Err(this),
AcquireOutcome::Exclusive => unsafe {
Ok(ManuallyDrop::take(
&mut mem::transmute::<Self, Arc<ManuallyDrop<T>>>(this)
.pointer
.as_mut(),
))
},
}
}
/// Constructs an [`Arc`] instance from a compatible value pointer.
///
/// # Safety
///
/// The pointer `raw_value` must have been created by leaking from a compatible *unpinned* container.
///
/// Containers are incompatible if their type parameter differs in a way that
/// makes the equivalent pointer reinterpretation cast invalid.
/// Otherwise:
///
/// ([`Arc`] and [`Rc`](`crate::Rc`) are compatible.
/// [`Box`] is compatible iff the internal reference count had been incremented to at least `1` at the time of leaking.)
///
/// For every time the instance that pointer points to was leaked,
/// this function must be called at most once.
///
/// The data `raw_value` points to may be in use only by [`Arc`].
#[must_use = "Implicitly dropping this handle is likely a mistake."]
pub unsafe fn from_raw(raw_value: NonNull<T>) -> Self {
debug_assert_ne!(
raw_value.as_ptr().cast::<()>() as usize,
0,
"Called `tiptoe::Arc::from_raw` with null pointer."
);
Self {
pointer: raw_value,
_phantom: PhantomData,
}
}
/// Constructs a [pinned](`core::pin`) [`Arc`] instance from a compatible value pointer.
///
/// # Safety
///
/// The pointer `raw_value` must have been created by leaking from a compatible container.
///
/// Containers are incompatible if their type parameter differs in a way that
/// makes the equivalent pointer reinterpretation cast invalid.
/// Otherwise:
///
/// ([`Arc`] and [`Rc`](`crate::Rc`) are compatible.
/// [`Box`] is compatible iff the internal reference count had been incremented to at least `1` at the time of leaking.)
///
/// For every time the instance that pointer points to was leaked,
/// this function must be called at most once.
///
/// The data `raw_value` points to may be in use only by [`Arc`].
#[must_use = "Implicitly dropping this handle is likely a mistake."]
pub unsafe fn pinned_from_raw(raw_value: NonNull<T>) -> Pin<Self> {
debug_assert_ne!(
raw_value.as_ptr().cast::<()>() as usize,
0,
"Called `tiptoe::Arc::from_raw` with null pointer."
);
Self {
pointer: raw_value,
_phantom: PhantomData,
}
.into()
}
#[must_use]
pub fn leak(this: Self) -> NonNull<T> {
let pointer = this.pointer;
mem::forget(this);
pointer
}
/// # Safety Notes
///
/// Keep in mind that the pinning invariants, including the drop guarantee, must still be upheld.
#[must_use]
pub fn leak_pinned(this: Pin<Self>) -> NonNull<T> {
let this = unsafe { Pin::into_inner_unchecked(this) };
let pointer = this.pointer;
mem::forget(this);
pointer
}
#[must_use]
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.pointer == other.pointer
}
#[must_use]
pub fn make_mut(this: &mut Pin<Self>) -> Pin<&mut T>
where
T: Sized + Clone,
{
match this.tip_toe().acquire() {
AcquireOutcome::Exclusive => (),
AcquireOutcome::Shared => *this = (&**this).clone().pipe(Self::pin),
}
unsafe {
Pin::new_unchecked(
mem::transmute_copy::<Pin<Self>, Self>(this)
.pointer
.as_mut(),
)
}
}
#[must_use]
pub fn get_mut(this: &mut Pin<Self>) -> Option<Pin<&mut T>> {
match this.tip_toe().acquire() {
AcquireOutcome::Shared => None,
AcquireOutcome::Exclusive => Some(unsafe {
Pin::new_unchecked(
mem::transmute_copy::<Pin<Self>, Self>(this)
.pointer
.as_mut(),
)
}),
}
}
/// Attempts to cast this [`Arc`] into once of concrete type `U`.
///
/// # Errors
///
/// Iff the underlying instance isn't a `U`.
pub fn downcast<U>(this: Self) -> Result<Arc<U>, Self>
where
T: Any,
U: Any + TipToed,
{
if Any::type_id(&*this) == TypeId::of::<U>() {
Ok(unsafe { Arc::from_raw(Arc::leak(this).cast()) })
} else {
Err(this)
}
}
/// Attempts to cast this [`Arc`] into once of concrete type `U`.
///
/// # Errors
///
/// Iff the underlying instance isn't a `U`.
pub fn downcast_pinned<U>(this: Pin<Self>) -> Result<Pin<Arc<U>>, Pin<Self>>
where
T: Any,
U: Any + TipToed,
{
if Any::type_id(&*this) == TypeId::of::<U>() {
Ok(unsafe { Arc::pinned_from_raw(Arc::leak_pinned(this).cast()) })
} else {
Err(this)
}
}
}