1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#![cfg_attr(feature = "pinned", feature(pin))]

//! This crate provides an `AsPin` trait. AsPin can be used in the same fashion as `AsRef` and `AsMut`.

#[cfg(feature = "pinned")]
pub mod implement {
    use std::marker::Unpin;
    use std::pin::PinMut;

    /// Converts a mutable reference into a pinned reference. See the [`pin` module].
    ///
    /// [`pin` module]: https://doc.rust-lang.org/nightly/std/pin/struct.PinMut.html
    ///
    /// # Examples
    /// ```
    /// #![feature(pin)]
    ///
    /// extern crate pinpoint;
    /// use pinpoint::AsPin;
    ///
    /// use std::pin::PinMut;
    ///
    /// let mut v = vec![5, 4, 3, 2, 1];
    /// let mut pin: PinMut<[u32]> = v.as_pin();
    ///
    /// pin.sort();
    ///
    /// assert_eq!(pin.as_ref(), [1, 2, 3, 4, 5]);
    ///
    /// ```
    pub trait AsPin<T: ?Sized + Unpin> {
        /// Performs the conversion.
        fn as_pin(&mut self) -> PinMut<T>;
    }

    ///////////////////////////////////////////////
    // GENERIC IMPL
    ///////////////////////////////////////////////

    impl<'a, T: ?Sized, U: ?Sized + Unpin> AsPin<U> for &'a mut T
    where
        T: AsPin<U>,
    {
        #[inline]
        fn as_pin(&mut self) -> PinMut<U> {
            (*self).as_pin()
        }
    }

    ///////////////////////////////////////////////
    // SLICE IMPLS
    ///////////////////////////////////////////////
    impl<T: Unpin> AsPin<[T]> for [T] {
        #[inline]
        fn as_pin(&mut self) -> PinMut<Self> {
            PinMut::new(self)
        }
    }

    ///////////////////////////////////////////////
    // OTHER IMPLS
    ///////////////////////////////////////////////
    impl<T: Unpin + ?Sized> AsPin<T> for Box<T> {
        #[inline]
        fn as_pin(&mut self) -> PinMut<T> {
            PinMut::new(self)
        }
    }

    impl<T: Unpin> AsPin<[T]> for Vec<T> {
        #[inline]
        fn as_pin(&mut self) -> PinMut<[T]> {
            PinMut::new(self)
        }
    }

    impl<T: Unpin> AsPin<Vec<T>> for Vec<T> {
        #[inline]
        fn as_pin(&mut self) -> PinMut<Vec<T>> {
            PinMut::new(self)
        }
    }

    impl AsPin<String> for String {
        #[inline]
        fn as_pin(&mut self) -> PinMut<String> {
            PinMut::new(self)
        }
    }
}

#[cfg(feature = "pinned")]
pub use self::implement::AsPin;