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