devela/data/dst/
buffer.rs

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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// devela::data::dst

use crate::{Array, ConstDefault, Deref, DerefMut, MaybeUninit, MemPod};

/// Represents the backing buffer for storing dynamically sized types.
///
/// # Safety
/// Must conform to the following rules:
/// - The `as_ref`/`as_mut` methods must return pointers to the same data.
/// - The pointer returned by `as_mut` must be stable until either a call to
///   `extend` or the value is moved (i.e. `let a = foo.as_mut().as_ptr();
///   let b = foo.as_mut().as_ptr(); assert!(a == b)` always holds).
/// - `extend` must not change any contained data
///   (but may extend with unspecified values).
pub unsafe trait DstBuf {
    /// Inner type of the buffer
    type Inner: MemPod;

    /// Get the buffer slice as shared reference.
    fn as_ref(&self) -> &[MaybeUninit<Self::Inner>];

    /// Get the buffer slice as an exclusive reference.
    fn as_mut(&mut self) -> &mut [MaybeUninit<Self::Inner>];

    /// Extend the buffer (fallible).
    fn extend(&mut self, len: usize) -> Result<(), ()>;

    /// Convert a byte count to a word count (rounding up).
    fn round_to_words(bytes: usize) -> usize {
        super::round_to_words::<Self::Inner>(bytes)
    }
}

// impl for an exclusive reference
#[rustfmt::skip]
unsafe impl<T, U> DstBuf for &mut T where U: MemPod, T: DstBuf<Inner = U> {
    type Inner = T::Inner;

    fn as_ref(&self) -> &[MaybeUninit<Self::Inner>] {
        (**self).as_ref()
    }
    fn as_mut(&mut self) -> &mut [MaybeUninit<Self::Inner>] {
        (**self).as_mut()
    }
    fn extend(&mut self, len: usize) -> Result<(), ()> {
        (**self).extend(len)
    }
}

// impl for array
unsafe impl<T: MemPod, const CAP: usize> DstBuf for [MaybeUninit<T>; CAP] {
    type Inner = T;

    fn as_ref(&self) -> &[MaybeUninit<Self::Inner>] {
        self
    }
    fn as_mut(&mut self) -> &mut [MaybeUninit<Self::Inner>] {
        self
    }
    fn extend(&mut self, len: usize) -> Result<(), ()> {
        if len > CAP {
            Err(())
        } else {
            Ok(())
        }
    }
}

/// Vector backed structures, can be used to auto-grow the allocation
///
/// # Examples
/// ```
/// # use {devela::data::DstQueue, core::mem::MaybeUninit};
/// let mut buf = DstQueue::<str, Vec<MaybeUninit<u8>>>::new();
/// buf.push_back_str("Hello world!");
/// buf.push_back_str("This is a very long string");
/// buf.push_back_str("The buffer should keep growing as it needs to");
/// for line in buf.iter() {
///   println!("{}", line);
/// }
/// ```
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "alloc")))]
unsafe impl<T: MemPod> DstBuf for crate::Vec<MaybeUninit<T>> {
    type Inner = T;
    fn as_ref(&self) -> &[MaybeUninit<Self::Inner>] {
        self
    }
    fn as_mut(&mut self) -> &mut [MaybeUninit<Self::Inner>] {
        self
    }
    fn extend(&mut self, len: usize) -> Result<(), ()> {
        if len > self.len() {
            self.resize(len, MaybeUninit::uninit());
            let cap = self.capacity();
            self.resize(cap, MaybeUninit::uninit());
        }
        Ok(())
    }
}

/// A static array for storing <abbr title="Dynamically sized
/// type">DST</abbr>s.
pub struct DstArray<T, const CAP: usize> {
    inner: Array<MaybeUninit<T>, CAP>,
}
impl<T, const CAP: usize> Deref for DstArray<T, CAP> {
    type Target = Array<MaybeUninit<T>, CAP>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}
impl<T, const CAP: usize> DerefMut for DstArray<T, CAP> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}
impl<T: MemPod, const CAP: usize> Default for DstArray<T, CAP> {
    fn default() -> Self {
        Self { inner: Array::new([MaybeUninit::uninit(); CAP]) }
    }
}
impl<T: MemPod, const CAP: usize> ConstDefault for DstArray<T, CAP> {
    const DEFAULT: Self = Self {
        inner: Array::new_bare([MaybeUninit::uninit(); CAP]),
    };
}
#[rustfmt::skip]
unsafe impl<T: MemPod, const CAP: usize> DstBuf for DstArray<T, CAP> {
    type Inner = T;
    fn as_ref(&self) -> &[MaybeUninit<Self::Inner>] {
        &self.inner
    }
    fn as_mut(&mut self) -> &mut [MaybeUninit<Self::Inner>] {
        &mut self.inner
    }
    fn extend(&mut self, len: usize) -> Result<(), ()> {
        if len > CAP { Err(()) } else { Ok(()) }
    }
}

/// A statically allocated buffer for storing <abbr title="Dynamically sized
/// type">DST</abbr>s with pointer alignment.
pub type DstArrayUsize<const CAP: usize> = DstArray<usize, CAP>;

/// A dynamically allocated buffer for storing <abbr title="Dynamically sized
/// type">DST</abbr>s with pointer alignment.
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "alloc")))]
pub type DstVecUsize = crate::Vec<MaybeUninit<usize>>;

// MAYBE
// /// A DST buffer backing onto a Vec.
// #[cfg(feature = "alloc")]
// #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "alloc")))]
// pub struct DstVec<T: MemPod>(crate::Vec<MaybeUninit<T>>);
// impl<T: MemPod> Deref for DstVec<T> {
//     type Target = Vec<MaybeUninit<T>>;
//
//     fn deref(&self) -> &Self::Target {
//         &self.0
//     }
// }
// impl<T: MemPod> DerefMut for DstVec<T> {
//     fn deref_mut(&mut self) -> &mut Self::Target {
//         &mut self.0
//     }
// }