scsys_traits/wrapper.rs
1/*
2 Appellation: wrapper <module>
3 Contrib: @FL03
4*/
5/// [IntoInner] is typically used for basic structures that wrap a single value.
6pub trait IntoInner {
7 type Inner;
8
9 fn into_inner(self) -> Self::Inner;
10}
11/// A [`RawWrapper`] is the base trait defining all so-called "wrapper" types.
12pub trait RawWrapper {
13 type Item;
14}
15/// The [`Wrapper`] trait is used to establish a common interface for all simplemented
16/// structures that "wrap" a single value. Essentially, any type capable of implementing
17/// `#[repr(transparent)]` can be considered a wrapper.
18pub trait Wrapper: RawWrapper {
19 /// returns a new instance of the wrapper initialized with the default value
20 fn new() -> Self
21 where
22 Self: Sized,
23 Self::Item: Default,
24 {
25 Self::from_value(Self::Item::default())
26 }
27 /// returns a new instance of the wrapper initialized with the given value
28 fn from_value(value: Self::Item) -> Self;
29 /// consumes the wrapper to return the stored value
30 fn into_inner(self) -> Self::Item;
31 /// returns an immutable reference to the stored value
32 fn get(&self) -> &Self::Item;
33 /// returns a mutable reference to the stored value
34 fn get_mut(&mut self) -> &mut Self::Item;
35}
36/// [`WrapperExt`] is an automatically implemented trait extending the [`Wrapper`] trait with
37/// additional
38pub trait WrapperExt: Wrapper {
39 /// [`replace`](core::mem::replace) replaces the value inside the wrapper with a new one,
40 /// returning the old value.
41 fn replace(&mut self, value: Self::Item) -> Self::Item {
42 core::mem::replace(self.get_mut(), value)
43 }
44 /// update the current value before returning a mutable reference to the wrapper
45 fn set(&mut self, value: Self::Item) -> &mut Self {
46 *self.get_mut() = value;
47 self
48 }
49 /// [`swap`](core::mem::swap) swaps the inner values of two instances.
50 fn swap(&mut self, other: &mut Self) {
51 core::mem::swap(self.get_mut(), other.get_mut())
52 }
53
54 fn take(&mut self) -> Self::Item
55 where
56 Self::Item: Default,
57 {
58 core::mem::take(self.get_mut())
59 }
60}
61
62pub trait Mapper<U> {
63 type Item<V>;
64
65 fn map<V, F>(self, f: F) -> Self::Item<V>
66 where
67 F: FnOnce(U) -> V;
68}
69
70/*
71 ************* Implementations *************
72*/
73impl<T, U> WrapperExt for T where T: Wrapper<Item = U> {}