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