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