-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy pathmod.rs
More file actions
2415 lines (2133 loc) · 70.2 KB
/
mod.rs
File metadata and controls
2415 lines (2133 loc) · 70.2 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
use core::{
borrow,
cmp::Ordering,
fmt, hash,
iter::FusedIterator,
marker::PhantomData,
mem::{self, ManuallyDrop, MaybeUninit},
ops::{self, Range, RangeBounds},
ptr::{self, NonNull},
slice,
};
#[cfg(feature = "zeroize")]
use zeroize::Zeroize;
use crate::{
len_type::{check_capacity_fits, LenType},
CapacityError,
};
mod drain;
mod storage {
use core::mem::MaybeUninit;
use crate::{
binary_heap::{BinaryHeapInner, BinaryHeapView},
deque::{DequeInner, DequeView},
len_type::LenType,
};
use super::{VecInner, VecView};
/// Trait defining how data for a container is stored.
///
/// There's two implementations available:
///
/// - [`OwnedVecStorage`]: stores the data in an array `[T; N]` whose size is known at compile
/// time.
/// - [`ViewVecStorage`]: stores the data in an unsized `[T]`.
///
/// This allows [`Vec`] to be generic over either sized or unsized storage. The [`vec`](super)
/// module contains a [`VecInner`] struct that's generic on [`VecStorage`],
/// and two type aliases for convenience:
///
/// - [`Vec<T, N>`](crate::vec::Vec) = `VecInner<T, OwnedStorage<T, N>>`
/// - [`VecView<T>`](crate::vec::VecView) = `VecInner<T, ViewStorage<T>>`
///
/// `Vec` can be unsized into `VecView`, either by unsizing coercions such as `&mut Vec -> &mut
/// VecView` or `Box<Vec> -> Box<VecView>`, or explicitly with
/// [`.as_view()`](crate::vec::Vec::as_view) or
/// [`.as_mut_view()`](crate::vec::Vec::as_mut_view).
///
/// This trait is sealed, so you cannot implement it for your own types. You can only use
/// the implementations provided by this crate.
///
/// [`VecInner`]: super::VecInner
/// [`Vec`]: super::Vec
/// [`VecView`]: super::VecView
#[allow(private_bounds)]
pub trait VecStorage<T>: VecSealedStorage<T> {}
pub trait VecSealedStorage<T> {
// part of the sealed trait so that no trait is publicly implemented by `OwnedVecStorage`
// besides `Storage`
fn borrow(&self) -> &[MaybeUninit<T>];
fn borrow_mut(&mut self) -> &mut [MaybeUninit<T>];
fn as_vec_view<LenT: LenType>(this: &VecInner<T, LenT, Self>) -> &VecView<T, LenT>
where
Self: VecStorage<T>;
fn as_vec_view_mut<LenT: LenType>(
this: &mut VecInner<T, LenT, Self>,
) -> &mut VecView<T, LenT>
where
Self: VecStorage<T>;
fn as_binary_heap_view<K>(this: &BinaryHeapInner<T, K, Self>) -> &BinaryHeapView<T, K>
where
Self: VecStorage<T>;
fn as_binary_heap_view_mut<K>(
this: &mut BinaryHeapInner<T, K, Self>,
) -> &mut BinaryHeapView<T, K>
where
Self: VecStorage<T>;
fn as_deque_view(this: &DequeInner<T, Self>) -> &DequeView<T>
where
Self: VecStorage<T>;
fn as_deque_view_mut(this: &mut DequeInner<T, Self>) -> &mut DequeView<T>
where
Self: VecStorage<T>;
}
#[cfg(feature = "zeroize")]
use zeroize::Zeroize;
// One sealed layer of indirection to hide the internal details (The MaybeUninit).
#[cfg_attr(feature = "zeroize", derive(Zeroize))]
pub struct VecStorageInner<T: ?Sized> {
pub(crate) buffer: T,
}
/// Implementation of [`VecStorage`] that stores the data in an array `[T; N]` whose size is
/// known at compile time.
pub type OwnedVecStorage<T, const N: usize> = VecStorageInner<[MaybeUninit<T>; N]>;
/// Implementation of [`VecStorage`] that stores the data in an unsized `[T]`.
pub type ViewVecStorage<T> = VecStorageInner<[MaybeUninit<T>]>;
impl<T, const N: usize> VecSealedStorage<T> for OwnedVecStorage<T, N> {
fn borrow(&self) -> &[MaybeUninit<T>] {
&self.buffer
}
fn borrow_mut(&mut self) -> &mut [MaybeUninit<T>] {
&mut self.buffer
}
fn as_vec_view<LenT: LenType>(this: &VecInner<T, LenT, Self>) -> &VecView<T, LenT>
where
Self: VecStorage<T>,
{
this
}
fn as_vec_view_mut<LenT: LenType>(
this: &mut VecInner<T, LenT, Self>,
) -> &mut VecView<T, LenT>
where
Self: VecStorage<T>,
{
this
}
fn as_binary_heap_view<K>(this: &BinaryHeapInner<T, K, Self>) -> &BinaryHeapView<T, K>
where
Self: VecStorage<T>,
{
this
}
fn as_binary_heap_view_mut<K>(
this: &mut BinaryHeapInner<T, K, Self>,
) -> &mut BinaryHeapView<T, K>
where
Self: VecStorage<T>,
{
this
}
fn as_deque_view(this: &DequeInner<T, Self>) -> &DequeView<T>
where
Self: VecStorage<T>,
{
this
}
fn as_deque_view_mut(this: &mut DequeInner<T, Self>) -> &mut DequeView<T>
where
Self: VecStorage<T>,
{
this
}
}
impl<T, const N: usize> VecStorage<T> for OwnedVecStorage<T, N> {}
impl<T> VecSealedStorage<T> for ViewVecStorage<T> {
fn borrow(&self) -> &[MaybeUninit<T>] {
&self.buffer
}
fn borrow_mut(&mut self) -> &mut [MaybeUninit<T>] {
&mut self.buffer
}
fn as_vec_view<LenT: LenType>(this: &VecInner<T, LenT, Self>) -> &VecView<T, LenT>
where
Self: VecStorage<T>,
{
this
}
fn as_vec_view_mut<LenT: LenType>(
this: &mut VecInner<T, LenT, Self>,
) -> &mut VecView<T, LenT>
where
Self: VecStorage<T>,
{
this
}
fn as_binary_heap_view<K>(this: &BinaryHeapInner<T, K, Self>) -> &BinaryHeapView<T, K>
where
Self: VecStorage<T>,
{
this
}
fn as_binary_heap_view_mut<K>(
this: &mut BinaryHeapInner<T, K, Self>,
) -> &mut BinaryHeapView<T, K>
where
Self: VecStorage<T>,
{
this
}
fn as_deque_view(this: &DequeInner<T, Self>) -> &DequeView<T>
where
Self: VecStorage<T>,
{
this
}
fn as_deque_view_mut(this: &mut DequeInner<T, Self>) -> &mut DequeView<T>
where
Self: VecStorage<T>,
{
this
}
}
impl<T> VecStorage<T> for ViewVecStorage<T> {}
}
pub use storage::{OwnedVecStorage, VecStorage, ViewVecStorage};
pub(crate) use storage::VecStorageInner;
pub use drain::Drain;
/// Base struct for [`Vec`] and [`VecView`], generic over the [`VecStorage`].
///
/// In most cases you should use [`Vec`] or [`VecView`] directly. Only use this
/// struct if you want to write code that's generic over both.
#[cfg_attr(feature = "zeroize", derive(Zeroize), zeroize(bound = "S: Zeroize"))]
pub struct VecInner<T, LenT: LenType, S: VecStorage<T> + ?Sized> {
phantom: PhantomData<T>,
len: LenT,
buffer: S,
}
/// A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
///
/// # Examples
///
/// ```
/// use heapless::Vec;
///
/// // A vector with a fixed capacity of 8 elements allocated on the stack
/// let mut vec = Vec::<_, 8>::new();
/// vec.push(1).unwrap();
/// vec.push(2).unwrap();
///
/// assert_eq!(vec.len(), 2);
/// assert_eq!(vec[0], 1);
///
/// assert_eq!(vec.pop(), Some(2));
/// assert_eq!(vec.len(), 1);
///
/// vec[0] = 7;
/// assert_eq!(vec[0], 7);
///
/// vec.extend([1, 2, 3].iter().cloned());
///
/// for x in &vec {
/// println!("{}", x);
/// }
/// assert_eq!(*vec, [7, 1, 2, 3]);
/// ```
///
/// In some cases, the const-generic might be cumbersome. `Vec` can coerce into a [`VecView`] to
/// remove the need for the const-generic:
///
/// ```rust
/// use heapless::{Vec, VecView};
///
/// let vec: Vec<u8, 10> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
/// let view: &VecView<_, _> = &vec;
/// ```
///
/// For uncommmon capacity values, or in generic scenarios, you may have to provide the `LenT`
/// generic yourself.
///
/// This should be the smallest unsigned integer type that your capacity fits in, or `usize` if you
/// don't want to consider this.
pub type Vec<T, const N: usize, LenT = usize> = VecInner<T, LenT, OwnedVecStorage<T, N>>;
/// A [`Vec`] with dynamic capacity
///
/// [`Vec`] coerces to `VecView`. `VecView` is `!Sized`, meaning it can only ever be used by
/// reference.
///
/// Unlike [`Vec`], `VecView` does not have an `N` const-generic parameter.
/// This has the ergonomic advantage of making it possible to use functions without needing to know
/// at compile-time the size of the buffers used, for example for use in `dyn` traits.
///
/// `VecView<T>` is to `Vec<T, N>` what `[T]` is to `[T; N]`.
///
/// ```rust
/// use heapless::{Vec, VecView};
///
/// let mut vec: Vec<u8, 10> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
/// let view: &VecView<_, _> = &vec;
/// assert_eq!(view, &[1, 2, 3, 4]);
///
/// let mut_view: &mut VecView<_, _> = &mut vec;
/// mut_view.push(5);
/// assert_eq!(vec, [1, 2, 3, 4, 5]);
/// ```
pub type VecView<T, LenT = usize> = VecInner<T, LenT, ViewVecStorage<T>>;
impl<T, LenT: LenType, const N: usize> Vec<T, N, LenT> {
const ELEM: MaybeUninit<T> = MaybeUninit::uninit();
const INIT: [MaybeUninit<T>; N] = [Self::ELEM; N]; // important for optimization of `new`
/// Constructs a new, empty vector with a fixed capacity of `N`
///
/// # Examples
///
/// ```
/// use heapless::Vec;
///
/// // allocate the vector on the stack
/// let mut x: Vec<u8, 16> = Vec::new();
///
/// // allocate the vector in a static variable
/// static mut X: Vec<u8, 16> = Vec::new();
/// ```
pub const fn new() -> Self {
const { check_capacity_fits::<LenT, N>() }
Self {
phantom: PhantomData,
len: LenT::ZERO,
buffer: VecStorageInner { buffer: Self::INIT },
}
}
/// Constructs a new vector with a fixed capacity of `N` and fills it
/// with the provided slice.
///
/// This is equivalent to the following code:
///
/// ```
/// use heapless::Vec;
///
/// let mut v: Vec<u8, 16> = Vec::new();
/// v.extend_from_slice(&[1, 2, 3]).unwrap();
/// ```
pub fn from_slice(other: &[T]) -> Result<Self, CapacityError>
where
T: Clone,
{
let mut v = Self::new();
v.extend_from_slice(other)?;
Ok(v)
}
/// Constructs a new vector with a fixed capacity of `N`, initializing
/// it with the provided array.
///
/// The length of the provided array, `M` may be equal to _or_ less than
/// the capacity of the vector, `N`.
///
/// If the length of the provided array is greater than the capacity of the
/// vector a compile-time error will be produced.
pub fn from_array<const M: usize>(src: [T; M]) -> Self {
const {
assert!(N >= M);
}
// We've got to copy `src`, but we're functionally moving it. Don't run
// any Drop code for T.
let src = ManuallyDrop::new(src);
if N == M {
Self {
phantom: PhantomData,
len: LenT::from_usize(N),
// NOTE(unsafe) ManuallyDrop<[T; M]> and [MaybeUninit<T>; N]
// have the same layout when N == M.
buffer: unsafe { mem::transmute_copy(&src) },
}
} else {
let mut v = Self::new();
for (src_elem, dst_elem) in src.iter().zip(v.buffer.buffer.iter_mut()) {
// NOTE(unsafe) src element is not going to drop as src itself
// is wrapped in a ManuallyDrop.
dst_elem.write(unsafe { ptr::read(src_elem) });
}
unsafe { v.set_len(M) };
v
}
}
/// Returns the contents of the vector as an array of length `M` if the length
/// of the vector is exactly `M`, otherwise returns `Err(self)`.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
/// let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
/// let array: [u8; 5] = buffer.into_array().unwrap();
/// assert_eq!(array, [1, 2, 3, 5, 8]);
/// ```
pub fn into_array<const M: usize>(self) -> Result<[T; M], Self> {
if self.len() == M {
// This is how the unstable `MaybeUninit::array_assume_init` method does it
let array = unsafe { (core::ptr::from_ref(&self.buffer).cast::<[T; M]>()).read() };
// We don't want `self`'s destructor to be called because that would drop all the
// items in the array
core::mem::forget(self);
Ok(array)
} else {
Err(self)
}
}
/// Clones a vec into a new vec
pub(crate) fn clone(&self) -> Self
where
T: Clone,
{
let mut new = Self::new();
// avoid `extend_from_slice` as that introduces a runtime check/panicking branch
for elem in self {
unsafe {
new.push_unchecked(elem.clone());
}
}
new
}
/// Casts the `LenT` type to a new type, preserving everything else about the vector.
///
/// This can be useful if you need to pass a `Vec<T, N, u8>` into a `Vec<T, N, usize>` for
/// example.
///
/// This will check at compile time if the `N` value will fit into `NewLenT`, and error if not.
pub fn cast_len_type<NewLenT: LenType>(self) -> Vec<T, N, NewLenT> {
const { check_capacity_fits::<NewLenT, N>() }
let this = ManuallyDrop::new(self);
// SAFETY: Pointer argument is derived from a reference, meeting the safety documented
// invariants. This also prevents double drops by wrapping `self` in `ManuallyDrop`.
Vec {
len: NewLenT::from_usize(this.len()),
buffer: unsafe { ptr::read(&this.buffer) },
phantom: PhantomData,
}
}
}
impl<T, LenT: LenType, S: VecStorage<T> + ?Sized> VecInner<T, LenT, S> {
/// Removes the specified range from the vector in bulk, returning all
/// removed elements as an iterator. If the iterator is dropped before
/// being fully consumed, it drops the remaining removed elements.
///
/// The returned iterator keeps a mutable borrow on the vector to optimize
/// its implementation.
///
/// # Panics
///
/// Panics if the starting point is greater than the end point or if
/// the end point is greater than the length of the vector.
///
/// # Leaking
///
/// If the returned iterator goes out of scope without being dropped (due to
/// [`mem::forget`], for example), the vector may have lost and leaked
/// elements arbitrarily, including elements outside the range.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
///
/// let mut v = Vec::<_, 8>::from_array([1, 2, 3]);
/// let u: Vec<_, 8> = v.drain(1..).collect();
/// assert_eq!(v, &[1]);
/// assert_eq!(u, &[2, 3]);
///
/// // A full range clears the vector, like `clear()` does.
/// v.drain(..);
/// assert_eq!(v, &[]);
/// ```
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, LenT>
where
R: RangeBounds<usize>,
{
// Memory Safety
//
// When the `Drain` is first created, it shortens the length of
// the source vector to make sure no uninitialized or moved-from elements
// are accessible at all if the `Drain`'s destructor never gets to run.
//
// `Drain` will `ptr::read` out the values to remove.
// When finished, remaining tail of the vec is copied back to cover
// the hole, and the vector length is restored to the new length.
//
let len = self.len();
let Range { start, end } = crate::slice::range(range, ..len);
unsafe {
// Set `self.vec` length's to `start`, to be safe in case `Drain` is leaked.
self.set_len(start);
let vec = NonNull::from(self.as_mut_view());
let range_slice = slice::from_raw_parts(vec.as_ref().as_ptr().add(start), end - start);
Drain {
tail_start: LenT::from_usize(end),
tail_len: LenT::from_usize(len - end),
iter: range_slice.iter(),
vec,
}
}
}
/// Get a reference to the `Vec`, erasing the `N` const-generic.
///
///
/// ```rust
/// # use heapless::{Vec, VecView};
/// let vec: Vec<u8, 10> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
/// let view: &VecView<u8, _> = vec.as_view();
/// ```
///
/// It is often preferable to do the same through type coerction, since `Vec<T, N>` implements
/// `Unsize<VecView<T>>`:
///
/// ```rust
/// # use heapless::{Vec, VecView};
/// let vec: Vec<u8, 10> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
/// let view: &VecView<u8, _> = &vec;
/// ```
#[inline]
pub fn as_view(&self) -> &VecView<T, LenT> {
S::as_vec_view(self)
}
/// Get a mutable reference to the `Vec`, erasing the `N` const-generic.
///
/// ```rust
/// # use heapless::{Vec, VecView};
/// let mut vec: Vec<u8, 10, u8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
/// let view: &mut VecView<u8, _> = vec.as_mut_view();
/// ```
///
/// It is often preferable to do the same through type coerction, since `Vec<T, N>` implements
/// `Unsize<VecView<T>>`:
///
/// ```rust
/// # use heapless::{Vec, VecView};
/// let mut vec: Vec<u8, 10, u8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
/// let view: &mut VecView<u8, _> = &mut vec;
/// ```
#[inline]
pub fn as_mut_view(&mut self) -> &mut VecView<T, LenT> {
S::as_vec_view_mut(self)
}
/// Returns a raw pointer to the vector’s buffer.
pub fn as_ptr(&self) -> *const T {
self.buffer.borrow().as_ptr().cast::<T>()
}
/// Returns a raw pointer to the vector’s buffer, which may be mutated through.
pub fn as_mut_ptr(&mut self) -> *mut T {
self.buffer.borrow_mut().as_mut_ptr().cast::<T>()
}
/// Extracts a slice containing the entire vector.
///
/// Equivalent to `&s[..]`.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
/// let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
/// assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);
/// ```
pub fn as_slice(&self) -> &[T] {
// NOTE(unsafe) avoid bound checks in the slicing operation
// &buffer[..self.len]
unsafe {
slice::from_raw_parts(
self.buffer.borrow().as_ptr().cast::<T>(),
self.len.into_usize(),
)
}
}
/// Extracts a mutable slice containing the entire vector.
///
/// Equivalent to `&mut s[..]`.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
/// let mut buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
/// let buffer_slice = buffer.as_mut_slice();
/// buffer_slice[0] = 9;
/// assert_eq!(buffer.as_slice(), &[9, 2, 3, 5, 8]);
/// ```
pub fn as_mut_slice(&mut self) -> &mut [T] {
// NOTE(unsafe) avoid bound checks in the slicing operation
// &mut buffer[..self.len]
unsafe {
slice::from_raw_parts_mut(
self.buffer.borrow_mut().as_mut_ptr().cast::<T>(),
self.len.into_usize(),
)
}
}
/// Returns the maximum number of elements the vector can hold.
pub fn capacity(&self) -> usize {
self.buffer.borrow().len()
}
/// Clears the vector, removing all values.
pub fn clear(&mut self) {
self.truncate(0);
}
/// Extends the vec from an iterator.
pub fn extend<I>(&mut self, iter: I) -> Result<(), CapacityError>
where
I: IntoIterator<Item = T>,
{
// Save current length to restore it later in case of an error.
let len = self.len();
iter.into_iter()
.try_for_each(|elem| self.push(elem))
.map_err(|_| {
// SAFETY: This is the length from before pushing elements for extending this
// vector.
unsafe { self.set_len(len) };
CapacityError
})
}
/// Clones and appends all elements in a slice to the `Vec`.
///
/// Iterates over the slice `other`, clones each element, and then appends
/// it to this `Vec`. The `other` vector is traversed in-order.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
///
/// let mut vec = Vec::<u8, 8>::new();
/// vec.push(1).unwrap();
/// vec.extend_from_slice(&[2, 3, 4]).unwrap();
/// assert_eq!(*vec, [1, 2, 3, 4]);
/// ```
pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError>
where
T: Clone,
{
pub fn extend_from_slice_inner<T, LenT: LenType>(
len: &mut LenT,
buf: &mut [MaybeUninit<T>],
other: &[T],
) -> Result<(), CapacityError>
where
T: Clone,
{
if len.into_usize() + other.len() > buf.len() {
// won't fit in the `Vec`; don't modify anything and return an error
Err(CapacityError)
} else {
for elem in other {
unsafe {
*buf.get_unchecked_mut(len.into_usize()) = MaybeUninit::new(elem.clone());
}
*len += LenT::one();
}
Ok(())
}
}
extend_from_slice_inner(&mut self.len, self.buffer.borrow_mut(), other)
}
/// Removes the last element from a vector and returns it, or `None` if it's empty
pub fn pop(&mut self) -> Option<T> {
if self.len == LenT::ZERO {
None
} else {
Some(unsafe { self.pop_unchecked() })
}
}
/// Appends an `item` to the back of the collection
///
/// Returns back the `item` if the vector is full.
pub fn push(&mut self, item: T) -> Result<(), T> {
if self.len() < self.capacity() {
unsafe { self.push_unchecked(item) }
Ok(())
} else {
Err(item)
}
}
/// Removes the last element from a vector and returns it
///
/// # Safety
///
/// This assumes the vec to have at least one element.
pub unsafe fn pop_unchecked(&mut self) -> T {
debug_assert!(!self.is_empty());
self.len -= LenT::one();
self.buffer
.borrow_mut()
.get_unchecked_mut(self.len.into_usize())
.as_ptr()
.read()
}
/// Appends an `item` to the back of the collection
///
/// # Safety
///
/// This assumes the vec is not full.
pub unsafe fn push_unchecked(&mut self, item: T) {
// NOTE(ptr::write) the memory slot that we are about to write to is uninitialized. We
// use `ptr::write` to avoid running `T`'s destructor on the uninitialized memory
debug_assert!(!self.is_full());
*self
.buffer
.borrow_mut()
.get_unchecked_mut(self.len.into_usize()) = MaybeUninit::new(item);
self.len += LenT::one();
}
/// Shortens the vector, keeping the first `len` elements and dropping the rest.
pub fn truncate(&mut self, len: usize) {
// This is safe because:
//
// * the slice passed to `drop_in_place` is valid; the `len > self.len` case avoids creating
// an invalid slice, and
// * the `len` of the vector is shrunk before calling `drop_in_place`, such that no value
// will be dropped twice in case `drop_in_place` were to panic once (if it panics twice,
// the program aborts).
unsafe {
// Note: It's intentional that this is `>` and not `>=`.
// Changing it to `>=` has negative performance
// implications in some cases. See rust-lang/rust#78884 for more.
if len > self.len() {
return;
}
let remaining_len = self.len() - len;
let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
self.len = LenT::from_usize(len);
ptr::drop_in_place(s);
}
}
/// Resizes the Vec in-place so that len is equal to `new_len`.
///
/// If `new_len` is greater than len, the Vec is extended by the
/// difference, with each additional slot filled with value. If
/// `new_len` is less than len, the Vec is simply truncated.
///
/// See also [`resize_default`](Self::resize_default).
pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), CapacityError>
where
T: Clone,
{
if new_len > self.capacity() {
return Err(CapacityError);
}
if new_len > self.len() {
while self.len() < new_len {
self.push(value.clone()).ok();
}
} else {
self.truncate(new_len);
}
Ok(())
}
/// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
///
/// If `new_len` is greater than `len`, the `Vec` is extended by the
/// difference, with each additional slot filled with `Default::default()`.
/// If `new_len` is less than `len`, the `Vec` is simply truncated.
///
/// See also [`resize`](Self::resize).
pub fn resize_default(&mut self, new_len: usize) -> Result<(), CapacityError>
where
T: Clone + Default,
{
self.resize(new_len, T::default())
}
/// Forces the length of the vector to `new_len`.
///
/// This is a low-level operation that maintains none of the normal
/// invariants of the type. Normally changing the length of a vector
/// is done using one of the safe operations instead, such as
/// [`truncate`], [`resize`], [`extend`], or [`clear`].
///
/// [`truncate`]: Self::truncate
/// [`resize`]: Self::resize
/// [`extend`]: core::iter::Extend
/// [`clear`]: Self::clear
///
/// # Safety
///
/// - `new_len` must be less than or equal to [`capacity()`].
/// - The elements at `old_len..new_len` must be initialized.
///
/// [`capacity()`]: Self::capacity
///
/// # Examples
///
/// This method can be useful for situations in which the vector
/// is serving as a buffer for other code, particularly over FFI:
///
/// ```no_run
/// # #![allow(dead_code)]
/// use heapless::Vec;
///
/// # // This is just a minimal skeleton for the doc example;
/// # // don't use this as a starting point for a real library.
/// # pub struct StreamWrapper { strm: *mut core::ffi::c_void }
/// # const Z_OK: i32 = 0;
/// # extern "C" {
/// # fn deflateGetDictionary(
/// # strm: *mut core::ffi::c_void,
/// # dictionary: *mut u8,
/// # dictLength: *mut usize,
/// # ) -> i32;
/// # }
/// # impl StreamWrapper {
/// pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
/// // Per the FFI method's docs, "32768 bytes is always enough".
/// let mut dict = Vec::new();
/// let mut dict_length = 0;
/// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
/// // 1. `dict_length` elements were initialized.
/// // 2. `dict_length` <= the capacity (32_768)
/// // which makes `set_len` safe to call.
/// unsafe {
/// // Make the FFI call...
/// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
/// if r == Z_OK {
/// // ...and update the length to what was initialized.
/// dict.set_len(dict_length);
/// Some(dict)
/// } else {
/// None
/// }
/// }
/// }
/// # }
/// ```
///
/// While the following example is sound, there is a memory leak since
/// the inner vectors were not freed prior to the `set_len` call:
///
/// ```
/// use core::iter::FromIterator;
/// use heapless::Vec;
///
/// let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
/// [
/// Vec::from_iter([1, 0, 0].iter().cloned()),
/// Vec::from_iter([0, 1, 0].iter().cloned()),
/// Vec::from_iter([0, 0, 1].iter().cloned()),
/// ]
/// .iter()
/// .cloned(),
/// );
/// // SAFETY:
/// // 1. `old_len..0` is empty so no elements need to be initialized.
/// // 2. `0 <= capacity` always holds whatever `capacity` is.
/// unsafe {
/// vec.set_len(0);
/// }
/// ```
///
/// Normally, here, one would use [`clear`] instead to correctly drop
/// the contents and thus not leak memory.
pub unsafe fn set_len(&mut self, new_len: usize) {
debug_assert!(new_len <= self.capacity());
self.len = LenT::from_usize(new_len);
}
/// Removes an element from the vector and returns it.
///
/// The removed element is replaced by the last element of the vector.
///
/// This does not preserve ordering, but is *O*(1).
///
/// # Panics
///
/// Panics if `index` is out of bounds.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
///
/// let mut v: Vec<_, 8> = Vec::new();
/// v.push("foo").unwrap();
/// v.push("bar").unwrap();
/// v.push("baz").unwrap();
/// v.push("qux").unwrap();
///
/// assert_eq!(v.swap_remove(1), "bar");
/// assert_eq!(&*v, ["foo", "qux", "baz"]);
///
/// assert_eq!(v.swap_remove(0), "foo");
/// assert_eq!(&*v, ["baz", "qux"]);
/// ```
pub fn swap_remove(&mut self, index: usize) -> T {
assert!(index < self.len());
unsafe { self.swap_remove_unchecked(index) }
}
/// Removes an element from the vector and returns it.
///
/// The removed element is replaced by the last element of the vector.
///
/// This does not preserve ordering, but is *O*(1).
///
/// # Safety
///
/// Assumes `index` within bounds.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
///
/// let mut v: Vec<_, 8> = Vec::new();
/// v.push("foo").unwrap();
/// v.push("bar").unwrap();
/// v.push("baz").unwrap();
/// v.push("qux").unwrap();
///
/// assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
/// assert_eq!(&*v, ["foo", "qux", "baz"]);
///
/// assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
/// assert_eq!(&*v, ["baz", "qux"]);
/// ```
pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T {
let length = self.len();
debug_assert!(index < length);
let value = ptr::read(self.as_ptr().add(index));
let base_ptr = self.as_mut_ptr();
ptr::copy(base_ptr.add(length - 1), base_ptr.add(index), 1);
self.len -= LenT::one();
value
}
/// Returns true if the vec is full
pub fn is_full(&self) -> bool {
self.len() == self.capacity()
}
/// Returns true if the vec is empty
pub fn is_empty(&self) -> bool {
self.len == LenT::ZERO
}
/// Returns `true` if `needle` is a prefix of the Vec.
///
/// Always returns `true` if `needle` is an empty slice.
///
/// # Examples
///
/// ```
/// use heapless::Vec;
///
/// let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
/// assert_eq!(v.starts_with(b""), true);
/// assert_eq!(v.starts_with(b"ab"), true);
/// assert_eq!(v.starts_with(b"bc"), false);
/// ```
pub fn starts_with(&self, needle: &[T]) -> bool
where
T: PartialEq,
{
let n = needle.len();
self.len() >= n && needle == &self[..n]
}
/// Returns `true` if `needle` is a suffix of the Vec.
///