aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / der / src / referenced.rs
| 1 | //! A module for working with referenced data. |
| 2 | |
| 3 | /// A trait for borrowing data from an owned struct |
| 4 | pub trait OwnedToRef { |
| 5 | /// The resulting type referencing back to Self |
| 6 | type Borrowed<'a> |
| 7 | where |
| 8 | Self: 'a; |
| 9 | |
| 10 | /// Creates a new object referencing back to the self for storage |
| 11 | fn owned_to_ref(&self) -> Self::Borrowed<'_>; |
| 12 | } |
| 13 | |
| 14 | /// A trait for cloning a referenced structure and getting owned objects |
| 15 | /// |
| 16 | /// This is the pendant to [`OwnedToRef`] |
| 17 | pub trait RefToOwned<'a> { |
| 18 | /// The resulting type after obtaining ownership. |
| 19 | type Owned: OwnedToRef<Borrowed<'a> = Self> |
| 20 | where |
| 21 | Self: 'a; |
| 22 | |
| 23 | /// Creates a new object taking ownership of the data |
| 24 | fn ref_to_owned(&self) -> Self::Owned; |
| 25 | } |
| 26 | |
| 27 | impl<T> OwnedToRef for Option<T> |
| 28 | where |
| 29 | T: OwnedToRef, |
| 30 | { |
| 31 | type Borrowed<'a> = Option<T::Borrowed<'a>> where T: 'a; |
| 32 | |
| 33 | fn owned_to_ref(&self) -> Self::Borrowed<'_> { |
| 34 | self.as_ref().map(|o| o.owned_to_ref()) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | impl<'a, T> RefToOwned<'a> for Option<T> |
| 39 | where |
| 40 | T: RefToOwned<'a> + 'a, |
| 41 | T::Owned: OwnedToRef, |
| 42 | { |
| 43 | type Owned = Option<T::Owned>; |
| 44 | fn ref_to_owned(&self) -> Self::Owned { |
| 45 | self.as_ref().map(|o| o.ref_to_owned()) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | #[cfg(feature = "alloc")] |
| 50 | mod allocating { |
| 51 | use super::{OwnedToRef, RefToOwned}; |
| 52 | use alloc::boxed::Box; |
| 53 | |
| 54 | impl<'a> RefToOwned<'a> for &'a [u8] { |
| 55 | type Owned = Box<[u8]>; |
| 56 | |
| 57 | fn ref_to_owned(&self) -> Self::Owned { |
| 58 | Box::from(*self) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | impl OwnedToRef for Box<[u8]> { |
| 63 | type Borrowed<'a> = &'a [u8]; |
| 64 | |
| 65 | fn owned_to_ref(&self) -> Self::Borrowed<'_> { |
| 66 | self.as_ref() |
| 67 | } |
| 68 | } |
| 69 | } |