unique_rc/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3#![warn(unsafe_op_in_unsafe_fn)]
4
5extern crate alloc;
6
7#[cfg(feature = "std")]
8use std::io;
9
10use alloc::{boxed::Box, rc::Rc, string::String, sync::Arc};
11use core::{
12    any::Any,
13    borrow::{Borrow, BorrowMut},
14    cmp,
15    error::Error,
16    ffi::CStr,
17    fmt,
18    future::Future,
19    hash::{Hash, Hasher},
20    iter::FusedIterator,
21    ops::{Deref, DerefMut},
22    pin::Pin,
23    task::{Context, Poll},
24};
25
26/// # Safety
27/// - The implementation of [`make_mut`] and [`to_unique`]
28///   must ensure that `strong_count` are set to 1 and there are no weak references
29///
30/// [`make_mut`]: #tymethod.make_mut
31/// [`to_unique`]: #method.to_unique
32pub unsafe trait MakeMut: Sized {
33    type T: ?Sized;
34
35    fn make_mut(this: &mut Self) -> &mut Self::T;
36
37    fn to_unique(mut this: Self) -> Self {
38        Self::make_mut(&mut this);
39        this
40    }
41}
42macro_rules! impl_make_mut {
43    ($({$($g:tt)*})? $ty:ty) => {
44        unsafe impl$(<$($g)*>)? MakeMut for Rc<$ty> {
45            type T = $ty;
46
47            fn make_mut(this: &mut Self) -> &mut Self::T {
48                Self::make_mut(this)
49            }
50        }
51        unsafe impl$(<$($g)*>)? MakeMut for Arc<$ty> {
52            type T = $ty;
53
54            fn make_mut(this: &mut Self) -> &mut Self::T {
55                Self::make_mut(this)
56            }
57        }
58        unsafe impl$(<$($g)*>)? MakeMut for UniqRc<$ty> {
59            type T = $ty;
60
61            fn make_mut(this: &mut Self) -> &mut Self::T {
62                this
63            }
64        }
65    };
66}
67impl_make_mut!({T: Clone} T);
68impl_make_mut!({T: Clone} [T]);
69impl_make_mut!(str);
70impl_make_mut!(CStr);
71
72#[cfg(feature = "std")]
73impl_make_mut!(std::path::Path);
74#[cfg(feature = "std")]
75impl_make_mut!(std::ffi::OsStr);
76
77macro_rules! impl_downcast {
78    ($UniqRc:ident : $(+ $auto:ident)*) => {
79        impl $UniqRc<dyn Any $(+ $auto)* + 'static> {
80            /// Like [`Box::downcast`]
81            ///
82            /// # Errors
83            /// - `self.is::<T>() == false`
84            pub fn downcast<T>(self) -> Result<$UniqRc<T>, Self>
85            where T: Any,
86            {
87                if self.is::<T>() {
88                    let raw: *mut (dyn Any $(+ $auto)*) = Self::into_raw(self);
89                    Ok(unsafe { $UniqRc::from_raw_unchecked(raw.cast()) })
90                } else {
91                    Err(self)
92                }
93            }
94        }
95    };
96}
97
98macro_rules! impl_rc { ($Rc:ident, $UniqRc:ident) => {
99
100#[doc = concat!("Owned [`", stringify!($Rc), "`], like [`Box`]\n\n")]
101#[doc = concat!("No other [`", stringify!($Rc), "`] or `Weak`\n")]
102#[repr(transparent)]
103#[derive(Eq, Default)]
104pub struct $UniqRc<T: ?Sized> {
105    rc: $Rc<T>,
106}
107
108impl<T: ?Sized + Hash> Hash for $UniqRc<T> {
109    fn hash<H: Hasher>(&self, state: &mut H) {
110        self.rc.hash(state);
111    }
112}
113
114impl<T: ?Sized + Ord> Ord for $UniqRc<T> {
115    fn cmp(&self, other: &Self) -> cmp::Ordering {
116        self.rc.cmp(&other.rc)
117    }
118}
119
120impl<T: ?Sized + PartialOrd> PartialOrd for $UniqRc<T> {
121    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
122        self.rc.partial_cmp(&other.rc)
123    }
124}
125
126impl<T: ?Sized + PartialEq> PartialEq for $UniqRc<T> {
127    fn eq(&self, other: &Self) -> bool {
128        self.rc == other.rc
129    }
130}
131
132impl<T: ?Sized> AsRef<T> for $UniqRc<T> {
133    fn as_ref(&self) -> &T {
134        self
135    }
136}
137
138impl<T: ?Sized> AsMut<T> for $UniqRc<T> {
139    fn as_mut(&mut self) -> &mut T {
140        self
141    }
142}
143
144impl<T: ?Sized> Borrow<T> for $UniqRc<T> {
145    fn borrow(&self) -> &T {
146        self
147    }
148}
149
150impl<T: ?Sized> BorrowMut<T> for $UniqRc<T> {
151    fn borrow_mut(&mut self) -> &mut T {
152        self
153    }
154}
155
156impl<T: ?Sized> Clone for $UniqRc<T>
157where $Rc<T>: MakeMut<T = T>,
158{
159    fn clone(&self) -> Self {
160        Self::new(MakeMut::to_unique(self.rc.clone()))
161    }
162}
163
164impl<T: ?Sized + Error> Error for $UniqRc<T> {
165    #[allow(deprecated)]
166    fn cause(&self) -> Option<&dyn Error> {
167        (**self).cause()
168    }
169
170    #[allow(deprecated)]
171    fn description(&self) -> &str {
172        (**self).description()
173    }
174
175    fn source(&self) -> Option<&(dyn Error + 'static)> {
176        (**self).source()
177    }
178}
179
180impl<T: ?Sized + fmt::Debug> fmt::Debug for $UniqRc<T> {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        self.rc.fmt(f)
183    }
184}
185
186impl<T: ?Sized + fmt::Display> fmt::Display for $UniqRc<T> {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        self.rc.fmt(f)
189    }
190}
191
192impl<T: ?Sized + fmt::Pointer> fmt::Pointer for $UniqRc<T> {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        self.rc.fmt(f)
195    }
196}
197
198impl<T: ?Sized> Deref for $UniqRc<T> {
199    type Target = T;
200
201    fn deref(&self) -> &Self::Target {
202        debug_assert_eq!($Rc::strong_count(&self.rc), 1);
203        &*self.rc
204    }
205}
206
207impl<T: ?Sized> DerefMut for $UniqRc<T> {
208    fn deref_mut(&mut self) -> &mut Self::Target {
209        debug_assert_eq!($Rc::strong_count(&self.rc), 1);
210        $Rc::get_mut(&mut self.rc).unwrap()
211    }
212}
213
214impl<T: ?Sized, U> FromIterator<U> for $UniqRc<T>
215where $Rc<T>: FromIterator<U> + MakeMut<T = T>,
216{
217    fn from_iter<I: IntoIterator<Item = U>>(iter: I) -> Self {
218        let rc = $Rc::from_iter(iter);
219        Self::new(rc)
220    }
221}
222
223impl<T: ?Sized, U> From<U> for $UniqRc<T>
224where $Rc<T>: MakeMut<T = T> + From<U>,
225{
226    fn from(value: U) -> Self {
227        Self::new(value.into())
228    }
229}
230
231impl<T: ?Sized> From<$UniqRc<T>> for Pin<$UniqRc<T>> {
232    fn from(this: $UniqRc<T>) -> Self {
233        $UniqRc::into_pin(this)
234    }
235}
236
237impl<T, const N: usize> From<$UniqRc<[T; N]>> for $UniqRc<[T]> {
238    fn from(this: $UniqRc<[T; N]>) -> Self {
239        let new = $UniqRc::into_raw(this);
240        unsafe { Self::from_raw_unchecked(new) }
241    }
242}
243
244impl Extend<$UniqRc<str>> for String {
245    fn extend<I: IntoIterator<Item = $UniqRc<str>>>(&mut self, iter: I) {
246        iter.into_iter().for_each(|s| self.push_str(&s))
247    }
248}
249
250impl FromIterator<$UniqRc<str>> for String {
251    fn from_iter<I: IntoIterator<Item = $UniqRc<str>>>(iter: I) -> Self {
252        let mut buf = String::new();
253        buf.extend(iter);
254        buf
255    }
256}
257
258impl<T, const N: usize> TryFrom<$UniqRc<[T]>> for $UniqRc<[T; N]> {
259    type Error = <$Rc<[T; N]> as TryFrom<$Rc<[T]>>>::Error;
260
261    fn try_from(this: $UniqRc<[T]>) -> Result<Self, Self::Error> {
262        match this.rc.try_into() {
263            Ok(rc) => unsafe {
264                Ok(Self::new_unchecked(rc))
265            },
266            Err(e) => Err(e),
267        }
268    }
269}
270
271#[allow(clippy::from_over_into)]
272impl<T: ?Sized> Into<$Rc<T>> for $UniqRc<T> {
273    fn into(self) -> $Rc<T> {
274        Self::into_rc(self)
275    }
276}
277
278impl From<$UniqRc<str>> for $Rc<[u8]> {
279    fn from(val: $UniqRc<str>) -> Self {
280        val.rc.into()
281    }
282}
283
284impl<T: ?Sized + Hasher> Hasher for $UniqRc<T> {
285    fn finish(&self) -> u64 {
286        (**self).finish()
287    }
288    fn write(&mut self, bytes: &[u8]) {
289        (**self).write(bytes)
290    }
291    fn write_u8(&mut self, i: u8) {
292        (**self).write_u8(i)
293    }
294    fn write_u16(&mut self, i: u16) {
295        (**self).write_u16(i)
296    }
297    fn write_u32(&mut self, i: u32) {
298        (**self).write_u32(i)
299    }
300    fn write_u64(&mut self, i: u64) {
301        (**self).write_u64(i)
302    }
303    fn write_u128(&mut self, i: u128) {
304        (**self).write_u128(i)
305    }
306    fn write_usize(&mut self, i: usize) {
307        (**self).write_usize(i)
308    }
309    fn write_i8(&mut self, i: i8) {
310        (**self).write_i8(i)
311    }
312    fn write_i16(&mut self, i: i16) {
313        (**self).write_i16(i)
314    }
315    fn write_i32(&mut self, i: i32) {
316        (**self).write_i32(i)
317    }
318    fn write_i64(&mut self, i: i64) {
319        (**self).write_i64(i)
320    }
321    fn write_i128(&mut self, i: i128) {
322        (**self).write_i128(i)
323    }
324    fn write_isize(&mut self, i: isize) {
325        (**self).write_isize(i)
326    }
327}
328
329impl<I: Iterator + ?Sized> Iterator for $UniqRc<I> {
330    type Item = I::Item;
331
332    fn next(&mut self) -> Option<I::Item> {
333        (**self).next()
334    }
335
336    fn size_hint(&self) -> (usize, Option<usize>) {
337        (**self).size_hint()
338    }
339
340    fn nth(&mut self, n: usize) -> Option<I::Item> {
341        (**self).nth(n)
342    }
343
344    fn last(self) -> Option<I::Item> {
345        self.fold(None, |_, ele| Some(ele))
346    }
347}
348
349impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for $UniqRc<I> {
350    fn next_back(&mut self) -> Option<I::Item> {
351        (**self).next_back()
352    }
353
354    fn nth_back(&mut self, n: usize) -> Option<I::Item> {
355        (**self).nth_back(n)
356    }
357}
358
359impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for $UniqRc<I> {
360    fn len(&self) -> usize {
361        (**self).len()
362    }
363}
364
365impl<I: FusedIterator + ?Sized> FusedIterator for $UniqRc<I> {}
366
367#[allow(clippy::non_send_fields_in_send_ty)]
368unsafe impl<T: ?Sized> Send for $UniqRc<T>
369where Box<T>: Send,
370{
371}
372
373impl<F: ?Sized + Future + Unpin> Future for $UniqRc<F> {
374    type Output = F::Output;
375
376    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
377        F::poll(Pin::new(&mut *self), cx)
378    }
379}
380
381#[cfg(feature = "std")]
382impl<R: io::Read + ?Sized> io::Read for $UniqRc<R> {
383    #[inline]
384    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
385        (**self).read(buf)
386    }
387
388    #[inline]
389    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
390        (**self).read_vectored(bufs)
391    }
392
393    #[inline]
394    fn read_to_end(&mut self, buf: &mut alloc::vec::Vec<u8>) -> io::Result<usize> {
395        (**self).read_to_end(buf)
396    }
397
398    #[inline]
399    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
400        (**self).read_to_string(buf)
401    }
402
403    #[inline]
404    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
405        (**self).read_exact(buf)
406    }
407}
408
409#[cfg(feature = "std")]
410impl<S: io::Seek + ?Sized> io::Seek for $UniqRc<S> {
411    #[inline]
412    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
413        (**self).seek(pos)
414    }
415
416    #[inline]
417    fn stream_position(&mut self) -> io::Result<u64> {
418        (**self).stream_position()
419    }
420}
421
422#[cfg(feature = "std")]
423impl<B: io::BufRead + ?Sized> io::BufRead for $UniqRc<B> {
424    #[inline]
425    fn fill_buf(&mut self) -> io::Result<&[u8]> {
426        (**self).fill_buf()
427    }
428
429    #[inline]
430    fn consume(&mut self, amt: usize) {
431        (**self).consume(amt)
432    }
433
434    #[inline]
435    fn read_until(&mut self, byte: u8, buf: &mut alloc::vec::Vec<u8>) -> io::Result<usize> {
436        (**self).read_until(byte, buf)
437    }
438
439    #[inline]
440    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
441        (**self).read_line(buf)
442    }
443}
444
445#[cfg(feature = "std")]
446impl<W: io::Write + ?Sized> io::Write for $UniqRc<W> {
447    #[inline]
448    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
449        (**self).write(buf)
450    }
451
452    #[inline]
453    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
454        (**self).write_vectored(bufs)
455    }
456
457    #[inline]
458    fn flush(&mut self) -> io::Result<()> {
459        (**self).flush()
460    }
461
462    #[inline]
463    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
464        (**self).write_all(buf)
465    }
466
467    #[inline]
468    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
469        (**self).write_fmt(fmt)
470    }
471}
472
473unsafe impl<T: ?Sized> Sync for $UniqRc<T>
474where Box<T>: Sync,
475{
476}
477
478impl<T: ?Sized> $UniqRc<T>
479where $Rc<T>: MakeMut<T = T>,
480{
481    pub fn new(rc: $Rc<T>) -> Self {
482        Self { rc: MakeMut::to_unique(rc) }
483    }
484
485    /// # Safety
486    #[doc = concat!("- Compliant with the safety of [`", stringify!($Rc), "::from_raw`]")]
487    pub unsafe fn from_raw(raw: *mut T) -> Self {
488        unsafe {
489            Self::new($Rc::from_raw(raw))
490        }
491    }
492}
493
494impl<T: ?Sized> $UniqRc<T> {
495    /// # Errors
496    /// - `rc` is shared, `strong_count != 1`
497    pub fn try_new(mut rc: $Rc<T>) -> Result<Self, $Rc<T>> {
498        if $Rc::get_mut(&mut rc).is_none() {
499            return Err(rc);
500        }
501
502        unsafe {
503            Ok(Self::new_unchecked(rc))
504        }
505    }
506
507    /// # Safety
508    /// - `strong_count == 1`
509    /// - No `Weak` exists
510    pub unsafe fn new_unchecked(rc: $Rc<T>) -> Self {
511        debug_assert_eq!($Rc::strong_count(&rc), 1);
512        Self { rc }
513    }
514
515    pub fn into_rc(this: Self) -> $Rc<T> {
516        this.rc
517    }
518
519    /// # Safety
520    /// - It is not allowed to change the strong and weak reference count
521    pub unsafe fn get_rc_unchecked(this: &Self) -> &$Rc<T> {
522        &this.rc
523    }
524
525    #[allow(clippy::ptr_cast_constness)]
526    pub fn into_raw(this: Self) -> *mut T {
527        $Rc::into_raw(this.rc) as *mut T
528    }
529
530    /// # Safety
531    /// - Compliant with the safety of [`from_raw`](#method.from_raw)
532    /// - Compliant with the safety of [`new_unchecked`](#method.new_unchecked)
533    pub unsafe fn from_raw_unchecked(raw: *mut T) -> Self {
534        unsafe {
535            Self::new_unchecked($Rc::from_raw(raw))
536        }
537    }
538
539    pub fn leak(this: Self) -> &'static mut T {
540        let ptr = Self::into_raw(this);
541        unsafe { &mut *ptr }
542    }
543
544    pub fn into_pin(this: Self) -> Pin<Self> {
545        unsafe { Pin::new_unchecked(this) }
546    }
547}
548
549impl<T> $UniqRc<T> {
550    pub fn new_value(value: T) -> Self {
551        Self { rc: $Rc::new(value) }
552    }
553
554    pub fn into_inner(this: Self) -> T {
555        $Rc::try_unwrap(this.rc).ok().expect(concat!(
556            "implement bug, inner ",
557            stringify!($Rc),
558            " strong_count != 1",
559        ))
560    }
561
562    pub fn pin(data: T) -> Pin<Self> {
563        unsafe { Pin::new_unchecked(Self::new_value(data)) }
564    }
565}
566
567impl_downcast!($UniqRc:);
568impl_downcast!($UniqRc: + Send);
569impl_downcast!($UniqRc: + Send + Sync);
570}}
571
572impl_rc!(Rc,    UniqRc);
573impl_rc!(Arc,   UniqArc);