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        $Rc::get_mut(&mut self.rc).unwrap()
215    }
216}
217
218impl<T: ?Sized, U> FromIterator<U> for $UniqRc<T>
219where $Rc<T>: FromIterator<U>,
220{
221    /// Proxy [`Rc::from_iter`]
222    ///
223    /// # Panics
224    ///
225    /// If the [`Rc`] returned by the implementation is shared, then panic
226    #[track_caller]
227    fn from_iter<I: IntoIterator<Item = U>>(iter: I) -> Self {
228        let mut rc = $Rc::from_iter(iter);
229        assert!($Rc::get_mut(&mut rc).is_some(),
230                "The FromIterator implementation supported by UniqRc \
231                 should not return shared Rc");
232        unsafe { Self::new_unchecked(rc) }
233    }
234}
235
236impl<T: ?Sized, U> From<U> for $UniqRc<T>
237where $Rc<T>: MakeMut<T = T> + From<U>,
238{
239    fn from(value: U) -> Self {
240        Self::new(value.into())
241    }
242}
243
244impl<T: ?Sized> From<$UniqRc<T>> for Pin<$UniqRc<T>> {
245    fn from(this: $UniqRc<T>) -> Self {
246        $UniqRc::into_pin(this)
247    }
248}
249
250impl<T, const N: usize> From<$UniqRc<[T; N]>> for $UniqRc<[T]> {
251    fn from(this: $UniqRc<[T; N]>) -> Self {
252        let new = $UniqRc::into_raw(this);
253        unsafe { Self::from_raw_unchecked(new) }
254    }
255}
256
257impl Extend<$UniqRc<str>> for String {
258    fn extend<I: IntoIterator<Item = $UniqRc<str>>>(&mut self, iter: I) {
259        iter.into_iter().for_each(|s| self.push_str(&s))
260    }
261}
262
263impl FromIterator<$UniqRc<str>> for String {
264    fn from_iter<I: IntoIterator<Item = $UniqRc<str>>>(iter: I) -> Self {
265        let mut buf = String::new();
266        buf.extend(iter);
267        buf
268    }
269}
270
271impl<T, const N: usize> TryFrom<$UniqRc<[T]>> for $UniqRc<[T; N]> {
272    type Error = <$Rc<[T; N]> as TryFrom<$Rc<[T]>>>::Error;
273
274    fn try_from(this: $UniqRc<[T]>) -> Result<Self, Self::Error> {
275        match this.rc.try_into() {
276            Ok(rc) => unsafe {
277                Ok(Self::new_unchecked(rc))
278            },
279            Err(e) => Err(e),
280        }
281    }
282}
283
284#[allow(clippy::from_over_into)]
285impl<T: ?Sized> Into<$Rc<T>> for $UniqRc<T> {
286    fn into(self) -> $Rc<T> {
287        Self::into_rc(self)
288    }
289}
290
291impl From<$UniqRc<str>> for $Rc<[u8]> {
292    fn from(val: $UniqRc<str>) -> Self {
293        val.rc.into()
294    }
295}
296
297impl<T: ?Sized + Hasher> Hasher for $UniqRc<T> {
298    fn finish(&self) -> u64 {
299        (**self).finish()
300    }
301    fn write(&mut self, bytes: &[u8]) {
302        (**self).write(bytes)
303    }
304    fn write_u8(&mut self, i: u8) {
305        (**self).write_u8(i)
306    }
307    fn write_u16(&mut self, i: u16) {
308        (**self).write_u16(i)
309    }
310    fn write_u32(&mut self, i: u32) {
311        (**self).write_u32(i)
312    }
313    fn write_u64(&mut self, i: u64) {
314        (**self).write_u64(i)
315    }
316    fn write_u128(&mut self, i: u128) {
317        (**self).write_u128(i)
318    }
319    fn write_usize(&mut self, i: usize) {
320        (**self).write_usize(i)
321    }
322    fn write_i8(&mut self, i: i8) {
323        (**self).write_i8(i)
324    }
325    fn write_i16(&mut self, i: i16) {
326        (**self).write_i16(i)
327    }
328    fn write_i32(&mut self, i: i32) {
329        (**self).write_i32(i)
330    }
331    fn write_i64(&mut self, i: i64) {
332        (**self).write_i64(i)
333    }
334    fn write_i128(&mut self, i: i128) {
335        (**self).write_i128(i)
336    }
337    fn write_isize(&mut self, i: isize) {
338        (**self).write_isize(i)
339    }
340}
341
342impl<I: Iterator + ?Sized> Iterator for $UniqRc<I> {
343    type Item = I::Item;
344
345    fn next(&mut self) -> Option<I::Item> {
346        (**self).next()
347    }
348
349    fn size_hint(&self) -> (usize, Option<usize>) {
350        (**self).size_hint()
351    }
352
353    fn nth(&mut self, n: usize) -> Option<I::Item> {
354        (**self).nth(n)
355    }
356
357    fn last(self) -> Option<I::Item> {
358        self.fold(None, |_, ele| Some(ele))
359    }
360}
361
362impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for $UniqRc<I> {
363    fn next_back(&mut self) -> Option<I::Item> {
364        (**self).next_back()
365    }
366
367    fn nth_back(&mut self, n: usize) -> Option<I::Item> {
368        (**self).nth_back(n)
369    }
370}
371
372impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for $UniqRc<I> {
373    fn len(&self) -> usize {
374        (**self).len()
375    }
376}
377
378impl<I: FusedIterator + ?Sized> FusedIterator for $UniqRc<I> {}
379
380#[allow(clippy::non_send_fields_in_send_ty)]
381unsafe impl<T: ?Sized> Send for $UniqRc<T>
382where Box<T>: Send,
383{
384}
385
386impl<F: ?Sized + Future + Unpin> Future for $UniqRc<F> {
387    type Output = F::Output;
388
389    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
390        F::poll(Pin::new(&mut *self), cx)
391    }
392}
393
394#[cfg(feature = "std")]
395impl<R: io::Read + ?Sized> io::Read for $UniqRc<R> {
396    #[inline]
397    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
398        (**self).read(buf)
399    }
400
401    #[inline]
402    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
403        (**self).read_vectored(bufs)
404    }
405
406    #[inline]
407    fn read_to_end(&mut self, buf: &mut alloc::vec::Vec<u8>) -> io::Result<usize> {
408        (**self).read_to_end(buf)
409    }
410
411    #[inline]
412    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
413        (**self).read_to_string(buf)
414    }
415
416    #[inline]
417    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
418        (**self).read_exact(buf)
419    }
420}
421
422#[cfg(feature = "std")]
423impl<S: io::Seek + ?Sized> io::Seek for $UniqRc<S> {
424    #[inline]
425    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
426        (**self).seek(pos)
427    }
428
429    #[inline]
430    fn stream_position(&mut self) -> io::Result<u64> {
431        (**self).stream_position()
432    }
433}
434
435#[cfg(feature = "std")]
436impl<B: io::BufRead + ?Sized> io::BufRead for $UniqRc<B> {
437    #[inline]
438    fn fill_buf(&mut self) -> io::Result<&[u8]> {
439        (**self).fill_buf()
440    }
441
442    #[inline]
443    fn consume(&mut self, amt: usize) {
444        (**self).consume(amt)
445    }
446
447    #[inline]
448    fn read_until(&mut self, byte: u8, buf: &mut alloc::vec::Vec<u8>) -> io::Result<usize> {
449        (**self).read_until(byte, buf)
450    }
451
452    #[inline]
453    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
454        (**self).read_line(buf)
455    }
456}
457
458#[cfg(feature = "std")]
459impl<W: io::Write + ?Sized> io::Write for $UniqRc<W> {
460    #[inline]
461    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
462        (**self).write(buf)
463    }
464
465    #[inline]
466    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
467        (**self).write_vectored(bufs)
468    }
469
470    #[inline]
471    fn flush(&mut self) -> io::Result<()> {
472        (**self).flush()
473    }
474
475    #[inline]
476    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
477        (**self).write_all(buf)
478    }
479
480    #[inline]
481    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
482        (**self).write_fmt(fmt)
483    }
484}
485
486#[cfg(feature = "serde")]
487impl<T: ?Sized + serde::Serialize> serde::Serialize for $UniqRc<T> {
488    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
489    where S: serde::Serializer,
490    {
491        (**self).serialize(serializer)
492    }
493}
494
495#[cfg(feature = "serde")]
496impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for $UniqRc<T> {
497    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
498    where D: serde::Deserializer<'de>,
499    {
500        T::deserialize(deserializer).map(Self::new_value)
501    }
502}
503
504unsafe impl<T: ?Sized> Sync for $UniqRc<T>
505where Box<T>: Sync,
506{
507}
508
509impl<T: ?Sized> $UniqRc<T>
510where $Rc<T>: MakeMut<T = T>,
511{
512    #[doc = concat!("Create `Self` from [`", stringify!($Rc), "`]")]
513    ///
514    /// If the `strong_count != 1`, clone the data
515    ///
516    /// # Examples
517    /// ```
518    /// # use unique_rc::UniqArc;
519    /// use std::sync::Arc;
520    ///
521    /// let arc = Arc::new(8);
522    /// let uniq_arc = UniqArc::new(arc);
523    /// ```
524    pub fn new(rc: $Rc<T>) -> Self {
525        Self { rc: MakeMut::to_unique(rc) }
526    }
527
528    /// Create from the raw pointer
529    ///
530    /// # Safety
531    #[doc = concat!("- Compliant with the safety of [`", stringify!($Rc), "::from_raw`]\n")]
532    #[doc = concat!("- Must from [`", stringify!($Rc), "`] instead of [`Box`]\n")]
533    pub unsafe fn from_raw(raw: *mut T) -> Self {
534        unsafe {
535            Self::new($Rc::from_raw(raw))
536        }
537    }
538}
539
540impl<T: ?Sized> $UniqRc<T> {
541    #[doc = concat!("Try create `Self` from [`", stringify!($Rc), "`]")]
542    ///
543    /// # Errors
544    /// - `rc` is shared, `strong_count != 1`
545    ///
546    /// # Examples
547    /// ```
548    /// # use unique_rc::UniqArc;
549    /// use std::sync::Arc;
550    ///
551    /// let arc = Arc::new(8);
552    /// let uniq_arc = UniqArc::try_new(arc);
553    /// assert!(uniq_arc.is_ok());
554    ///
555    /// let arc = Arc::new(8);
556    /// let uniq_arc = UniqArc::try_new(arc.clone());
557    /// assert!(uniq_arc.is_err());
558    /// ```
559    pub fn try_new(mut rc: $Rc<T>) -> Result<Self, $Rc<T>> {
560        if $Rc::get_mut(&mut rc).is_none() {
561            return Err(rc);
562        }
563
564        unsafe {
565            Ok(Self::new_unchecked(rc))
566        }
567    }
568
569    #[doc = concat!("Unchecked create `Self` from [`", stringify!($Rc), "`]")]
570    ///
571    /// # Safety
572    /// - Must `strong_count == 1`
573    /// - No `Weak` exists
574    pub unsafe fn new_unchecked(rc: $Rc<T>) -> Self {
575        debug_assert_eq!($Rc::strong_count(&rc), 1);
576        Self { rc }
577    }
578
579    #[doc = concat!("Unwrap into [`", stringify!($Rc), "`]")]
580    pub fn into_rc(this: Self) -> $Rc<T> {
581        this.rc
582    }
583
584    #[doc = concat!("Get wrapped [`", stringify!($Rc), "`]")]
585    ///
586    /// # Safety
587    /// - It is not allowed to change the strong and weak reference count
588    pub unsafe fn get_rc_unchecked(this: &Self) -> &$Rc<T> {
589        &this.rc
590    }
591
592    #[allow(clippy::ptr_cast_constness)]
593    pub fn into_raw(this: Self) -> *mut T {
594        $Rc::into_raw(this.rc) as *mut T
595    }
596
597    /// # Safety
598    /// - Compliant with the safety of [`from_raw`](#method.from_raw)
599    /// - Compliant with the safety of [`new_unchecked`](#method.new_unchecked)
600    pub unsafe fn from_raw_unchecked(raw: *mut T) -> Self {
601        unsafe {
602            Self::new_unchecked($Rc::from_raw(raw))
603        }
604    }
605
606    #[doc = concat!(
607        "Consumes and leaks the [`",
608        stringify!($UniqRc),
609        "`], returning a mutable reference, `&'static mut T.`"
610    )]
611    pub fn leak(this: Self) -> &'static mut T {
612        let ptr = Self::into_raw(this);
613        unsafe { &mut *ptr }
614    }
615
616    pub fn into_pin(this: Self) -> Pin<Self> {
617        unsafe { Pin::new_unchecked(this) }
618    }
619}
620
621impl<T> $UniqRc<T> {
622    /// Create `Self` from `value`, like `UniqRc::new(Rc::new(value))`
623    ///
624    /// # Examples
625    /// ```
626    /// # use unique_rc::UniqArc;
627    /// let uniq_arc = UniqArc::new_value(8);
628    /// assert_eq!(*uniq_arc, 8);
629    /// ```
630    pub fn new_value(value: T) -> Self {
631        Self { rc: $Rc::new(value) }
632    }
633
634    /// Into inner value
635    pub fn into_inner(this: Self) -> T {
636        $Rc::try_unwrap(this.rc).ok().expect(concat!(
637            "implement bug, inner ",
638            stringify!($Rc),
639            " strong_count != 1",
640        ))
641    }
642
643    #[doc = concat!("Create pinned [`", stringify!($UniqRc), "`]")]
644    ///
645    /// # Examples
646    /// ```
647    /// # use unique_rc::UniqArc;
648    /// let uniq_arc = UniqArc::pin(8);
649    /// assert_eq!(*uniq_arc, 8);
650    /// ```
651    pub fn pin(data: T) -> Pin<Self> {
652        unsafe { Pin::new_unchecked(Self::new_value(data)) }
653    }
654}
655
656impl_downcast!($UniqRc:);
657impl_downcast!($UniqRc: + Send);
658impl_downcast!($UniqRc: + Send + Sync);
659}}
660
661impl_rc!(Rc,    UniqRc);
662impl_rc!(Arc,   UniqArc);