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