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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#![no_std]
mod trait_impls;
use core::{mem::MaybeUninit, ptr::addr_of_mut};
#[derive(Debug)]
pub enum Error {
NotEnoughCapacity,
}
pub type Result<T> = core::result::Result<T, Error>;
/// A Vec-like (but non-growing) stack-allocated array.
// #[derive(Hash)]
pub struct PushArray<T, const CAP: usize> {
buf: [MaybeUninit<T>; CAP],
len: usize,
}
impl<T, const CAP: usize> PushArray<T, CAP> {
#[inline]
const fn array_of_uninit() -> [MaybeUninit<T>; CAP] {
// Safety: safe since this is an array of `MaybeUninit`s and they don't require initialization
unsafe { MaybeUninit::uninit().assume_init() }
}
/// Create an empty [`PushArray`] with the given capacity.
/// ```
/// # use pushy::PushArray;
/// let mut arr: PushArray<u8, 5> = PushArray::new();
///
/// assert!(arr.is_empty());
/// assert_eq!(arr.len(), 0);
/// assert_eq!(arr.initialized(), &[]);
/// ```
pub const fn new() -> Self {
let buf = Self::array_of_uninit();
Self { buf, len: 0 }
}
/// Returns the amount of initialized elements in this [`PushArray`].
/// ```
/// # use pushy::PushArray;
/// let mut arr: PushArray<u32, 5> = PushArray::new();
/// assert_eq!(arr.len(), 0);
///
/// arr.push(0);
///
/// assert_eq!(arr.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.len
}
/// Returns true if this [`PushArray`] is empty.
///
/// ```
/// # use pushy::PushArray;
/// let mut arr: PushArray<u32, 5> = PushArray::new();
/// assert!(arr.is_empty());
///
/// arr.push(0);
///
/// assert_eq!(arr.is_empty(), false);
/// ```
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Returns a reference to an initialized element of the array.
///
/// Returns `None` if the given index is out-of-bounds or not initialized.
///
/// ```
/// # use pushy::PushArray;
/// let mut arr: PushArray<u8, 3> = PushArray::new();
///
/// arr.push_str("Hey").unwrap();
///
/// assert_eq!(arr.get(0), Some(&b'H'));
/// assert_eq!(arr.get(1), Some(&b'e'));
/// assert_eq!(arr.get(2), Some(&b'y'));
/// assert_eq!(arr.get(3), None);
/// ```
pub fn get(&self, index: usize) -> Option<&T> {
// Safety: only called after we've made sure that the
// element in the given index is in-bounds and initialized
let get_elem = || unsafe { self.get_unchecked(index) };
(self.len > index).then(get_elem)
}
/// Returns a mutable reference to an initialized element of the array.
///
/// Returns `None` if the given index is out-of-bounds or not initialized.
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
// Safety: only called after we've made sure that the
// element in the given index is in-bounds and initialized
(self.len > index).then(|| unsafe { self.get_unchecked_mut(index) })
}
/// Returns a reference to an element without doing bounds
/// checking.
///
/// For a safe alternative see [`get`].
///
/// # Safety
///
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
/// even if the resulting reference is not used.
///
/// This method does not guarantee that the element returned is properly initialized.
///
/// [`get`]: PushArray::get
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
pub unsafe fn get_unchecked(&self, index: usize) -> &T {
self.buf.get_unchecked(index).assume_init_ref()
}
/// Returns a mutable reference to an element without doing bounds
/// checking.
///
/// For a safe alternative see [`get_mut`].
///
/// # Safety
///
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
/// even if the resulting reference is not used.
///
/// This method does not guarantee that the element returned is properly initialized.
///
/// [`get_mut`]: PushArray::get_mut
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
self.buf.get_unchecked_mut(index).assume_init_mut()
}
/// Pushes an element to the back of the [`PushArray`] without
/// checking the boundaries of the array first.
///
/// # Safety
///
/// The programmer must ensure this function does not push data after the end of the buffer, which would cause undefined behavior.
pub unsafe fn push_unchecked(&mut self, value: T) {
let ptr = self.buf.as_mut_ptr();
addr_of_mut!(*ptr)
.add(self.len)
.write(MaybeUninit::new(value));
self.len += 1;
}
/// Push an element to the end of this array after making sure
/// that the array has enough space to hold it.
///
/// ```
/// # use pushy::PushArray;
/// let mut arr: PushArray<u32, 2> = PushArray::new();
///
/// assert!(arr.push_checked(5).is_ok());
/// assert!(arr.push_checked(20).is_ok());
///
/// // Not enough capacity!
/// assert!(arr.push_checked(9).is_err());
/// ```
pub fn push_checked(&mut self, value: T) -> Result<()> {
(self.len < CAP)
.then(|| unsafe { self.push_unchecked(value) })
.ok_or(Error::NotEnoughCapacity)
}
/// Push an element to the back of this [`PushArray`].
///
/// # Panics
///
/// Panics if the capacity of this array is overrun.
///
/// ```
/// # use pushy::PushArray;
/// let mut bytes: PushArray<u8, 2> = PushArray::new();
/// bytes.push(b'H');
/// bytes.push(b'i');
///
/// assert_eq!(bytes.as_str().unwrap(), "Hi");
/// ```
pub fn push(&mut self, value: T) {
self.push_checked(value).expect("overflow in PushArray!")
}
/// Push all elements of the given array at the end of the [`PushArray`].
pub fn push_array<const M: usize>(&mut self, array: [T; M]) -> Result<()> {
if self.len + M > CAP {
return Err(Error::NotEnoughCapacity);
}
unsafe {
// Safety: we've just checked that there is enough capacity to
// push these elements into our array.
(self.as_mut_ptr().add(self.len) as *mut [T; M]).write(array);
}
self.len += M;
Ok(())
}
/// Removes the last element from the `PushArray`.
pub fn pop(&mut self) -> Option<T> {
self.len = self.len.checked_sub(1)?;
let mut popped = MaybeUninit::uninit();
unsafe {
let ptr = self.as_ptr().add(self.len) as *const T;
popped.write(ptr.read());
// Safety: we've just written to `popped`, therefore we
// can assume it's uninitialized
Some(popped.assume_init())
}
}
/// Gets a pointer to the first element of the array.
///
/// # Safety
///
/// * There is no guarantee that the first element pointed to is initialized.
///
/// * There is no guarantee that the first element exists (if the capacity allocated was zero).
pub unsafe fn as_ptr(&self) -> *const T {
&self.buf as *const [MaybeUninit<T>] as *const T
}
/// Gets a mutable pointer to the first element of the array.
///
/// # Safety
///
/// * There is no guarantee that the first element pointed to is initialized.
///
/// * There is no guarantee that the first element exists (if the capacity allocated was zero).
pub unsafe fn as_mut_ptr(&mut self) -> *mut T {
&mut self.buf as *mut [MaybeUninit<T>] as *mut T
}
/// Returns the initialized elements of this [`PushArray`].
///
/// Alias to [`PushArray::initialized`].
pub fn as_slice(&self) -> &[T] {
self.initialized()
}
/// Returns the initialized elements of this [`PushArray`].
pub fn initialized(&self) -> &[T] {
// Safety:
//
// * The elements given by `self.as_ptr()` are properly aligned since they come from
// an array (and the memory layout of MaybeUninit<T> is the same as the memory layout of T)
//
// * The slice will be created only with initialized values since we know that `self.len` is
// the amount of properly initialized elements in our array.
unsafe { core::slice::from_raw_parts(self.as_ptr(), self.len) }
}
/// Returns the initialized elements of this [`PushArray`].
pub fn initialized_mut(&mut self) -> &mut [T] {
// Safety:
//
// * The elements given by `self.as_mut_ptr()` are properly aligned since they come from
// an array (and the memory layout of MaybeUninit<T> is the same as the memory layout of T)
//
// * The slice will be created only with initialized values since we know that `self.len` is
// the amount of properly initialized elements in our array.
unsafe { core::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
}
/// Checks if all elements of this [`PushArray`] are initialized.
///
/// ```
/// # use pushy::PushArray;
/// let mut bytes: PushArray<u8, 5> = PushArray::new();
/// assert_eq!(bytes.is_fully_initialized(), false);
///
/// bytes.push_str("Hello").unwrap();
///
/// assert!(bytes.is_fully_initialized());
/// ```
pub fn is_fully_initialized(&self) -> bool {
self.len == CAP
}
/// Converts this [`PushArray<T; N>`](PushArray) into `[T; N]`, if all `N`
/// elements allocated are initialized.
///
/// ```
/// # use pushy::PushArray;
/// let mut bytes: PushArray<i8, 2> = PushArray::new();
/// bytes.push(1);
/// bytes.push(5);
///
/// assert_eq!(bytes.into_array(), Ok([1, 5]));
/// ```
pub fn into_array(self) -> core::result::Result<[T; CAP], Self> {
if self.is_fully_initialized() {
// Safety: it's ok to convert this PushArray into an array
// since all elements are initialized and the memory layout
// of [MaybeUninit<T>; N] and [T; N] is the same
let array = unsafe { self.into_array_unchecked() };
Ok(array)
} else {
Err(self)
}
}
/// Converts this [`PushArray<T; N>`](PushArray) into `[T; N]` without
/// checking if all `N` elements are initialized.
///
/// # Safety
///
/// Calling this function with a [`PushArray`] that is not fully initialized
/// results in unknown behavior.
///
/// ```
/// # use pushy::PushArray;
/// let mut bytes: PushArray<i8, 2> = PushArray::new();
/// bytes.push_array([2, 3]).unwrap();
///
/// // Safe to convert to array since all elements are initialized
/// let array = unsafe { bytes.into_array_unchecked() };
///
/// assert_eq!(array, [2, 3]);
/// ```
pub unsafe fn into_array_unchecked(self) -> [T; CAP] {
let ptr = self.as_ptr() as *const [T; CAP];
ptr.read()
}
/// Clear the [`PushArray`]. All initialized elements will be dropped.
///
/// ```
/// # use pushy::PushArray;
/// let mut bytes: PushArray<u8, 5> = PushArray::new();
/// bytes.push_str("Hello").unwrap();
///
/// assert_eq!(
/// bytes.as_str().unwrap(),
/// "Hello"
/// );
///
/// // Logically clear this array
/// bytes.clear();
///
/// assert_eq!(
/// bytes.as_str().unwrap(),
/// ""
/// );
/// ```
pub fn clear(&mut self) {
unsafe {
core::ptr::drop_in_place(self.initialized_mut());
}
self.len = 0;
}
}
impl<T: Copy, const CAP: usize> PushArray<T, CAP> {
/// Copy the elements from the given slice into the end of the [`PushArray`].
///
// ```
// # use pushy::PushArray;
// let mut bytes: PushArray<u8, 5> = PushArray::new();
// bytes.copy_from_slice(b"Hello").unwrap();
//
// assert_eq!(bytes.as_str(), Some("Hello"));
// ```
pub fn copy_from_slice(&mut self, slice: &[T]) -> Result<()> {
if self.len + slice.len() > CAP {
return Err(Error::NotEnoughCapacity);
}
// Safety: we've just checked that there is enough storage
// to hold the new elements.
//
// We also know these elements are trivially copiable since they implement Copy.
unsafe {
core::ptr::copy_nonoverlapping(
slice.as_ptr(),
self.as_mut_ptr().add(self.len),
slice.len(),
);
}
self.len += slice.len();
Ok(())
}
}
impl<const CAP: usize> PushArray<u8, CAP> {
/// Returns the bytes of this [`PushArray`] as a `&str` if they're valid UTF-8.
/// ```
/// # use pushy::PushArray;
/// let mut bytes: PushArray<u8, 11> = PushArray::new();
/// bytes.push_str("Hello").unwrap();
/// assert_eq!(bytes.as_str(), Some("Hello"));
///
/// bytes.push_str(" World").unwrap();
/// assert_eq!(bytes.as_str(), Some("Hello World"));
/// ```
pub fn as_str(&self) -> Option<&str> {
core::str::from_utf8(self.initialized()).ok()
}
/// Push a UTF-8 string to the back of this [`PushArray`].
///
/// ```
/// # use pushy::PushArray;
/// let mut bytes: PushArray<u8, 11> = PushArray::new();
///
/// assert_eq!(bytes.as_str(), Some(""));
/// bytes.push_str("Hello").unwrap();
/// assert_eq!(bytes.as_str(), Some("Hello"));
/// ```
pub fn push_str(&mut self, value: &str) -> Result<()> {
let bytes = value.as_bytes();
self.copy_from_slice(bytes)
}
}