-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathlib.rs
2642 lines (2543 loc) · 91.4 KB
/
lib.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
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
//! **Note:** the complete list of things **not** available when using `default-features = false`
//! for `#![no_std]` compatibility is as follows:
//! - [`StaticVec::sorted`]
//! - [`StaticVec::into_vec`] (and the corresponding [`Into`] impl)
//! - [`StaticVec::from_vec`] (and the corresponding [`From`] impl)
//! - the implementation of the [`Read`](std::io::Read) trait for [`StaticVec`]
//! - the implementation of the [`BufRead`](std::io::BufRead) trait for [`StaticVec`]
//! - the implementation of the [`io::Write`](std::io::Write) trait for [`StaticVec`]
//! - the implementation of [`From`] for [`StaticString`](crate::string::StaticString) from
//! [`String`](alloc::string::String)
//! - the implementations of [`PartialEq`] and [`PartialOrd`] against
//! [`String`](alloc::string::String) for [`StaticString`](crate::string::StaticString)
//! - the implementation of [`Error`](std::error::Error) for [`StringError`]
//! - the `bounds_to_string` function unique to this crate and implemented by several of the
//! iterators in it
#![no_std]
#![allow(
// Clippy wants every single instance of the word "StaticVec" to be in syntax-highlight
// backticks, which IMO looks way too "noisy" when actually rendered.
clippy::doc_markdown,
// Clippy thinks inline always is a bad idea even for the most simple of one-liners, so
// IMO it's just not a particularly helpful lint.
clippy::inline_always,
// The "if-let" syntax Clippy recommends as an alternative to "match" in this lint is
// generally way less readable IMO.
clippy::match_bool,
// Without this, every single use of const generics is warned against.
incomplete_features
)]
#![feature(
const_assume,
const_evaluatable_checked,
const_fn,
const_fn_floating_point_arithmetic,
const_fn_fn_ptr_basics,
const_fn_union,
const_generics,
const_intrinsic_copy,
const_maybe_uninit_as_ptr,
const_maybe_uninit_assume_init,
const_mut_refs,
const_panic,
const_precise_live_drops,
const_ptr_is_null,
const_ptr_offset,
const_ptr_offset_from,
const_ptr_read,
const_ptr_write,
const_raw_ptr_deref,
const_raw_ptr_to_usize_cast,
// this should be called `const_interior_mutability` IMO
const_refs_to_cell,
const_replace,
const_slice_from_raw_parts,
const_swap,
const_trait_impl,
core_intrinsics,
doc_cfg,
exact_size_is_empty,
inline_const,
maybe_uninit_extra,
maybe_uninit_ref,
maybe_uninit_uninit_array,
pattern,
slice_partition_dedup,
specialization,
trusted_len,
untagged_unions
)]
#![cfg_attr(feature = "std", feature(read_initializer))]
use core::cmp::{Ord, PartialEq};
use core::intrinsics::assume;
#[doc(hidden)]
pub use core::iter::FromIterator;
use core::marker::PhantomData;
use core::mem::{size_of, MaybeUninit};
use core::ops::{
Add, Bound::Excluded, Bound::Included, Bound::Unbounded, Div, Mul, RangeBounds, Sub,
};
use core::ptr;
pub use crate::errors::{CapacityError, PushCapacityError};
pub use crate::heap::{
StaticHeap, StaticHeapDrainSorted, StaticHeapIntoIterSorted, StaticHeapPeekMut,
};
pub use crate::iterators::{
StaticVecDrain, StaticVecIntoIter, StaticVecIterConst, StaticVecIterMut, StaticVecSplice,
};
pub use crate::string::{string_utils, StaticString, StringError};
use crate::utils::{
const_min, quicksort_internal, reverse_copy, slice_from_raw_parts, slice_from_raw_parts_mut,
};
#[cfg(any(feature = "std", rustdoc))]
extern crate alloc;
#[cfg(any(feature = "std", rustdoc))]
use alloc::vec::Vec;
#[cfg(feature = "std")]
extern crate std;
mod iterators;
#[macro_use]
mod macros;
#[doc(hidden)]
mod errors;
#[doc(hidden)]
mod heap;
#[doc(hidden)]
mod string;
pub(crate) mod trait_impls;
#[doc(hidden)]
pub mod utils;
/// A [`Vec`](alloc::vec::Vec)-like struct (mostly directly API-compatible where it can be)
/// implemented with const generics around an array of fixed `N` capacity.
pub struct StaticVec<T, const N: usize> {
// We create this field in an uninitialized state, and write to it element-wise as needed via
// pointer methods. At no time should the regular `assume_init` function *ever* be called through
// it unless an abundantly obviously-not-UB reason is present or a clear explanation is provided
// in comments. At this time, we only use `assume_init_read` and `assume_init_mut` (soundly, and
// for good reasons) in about two places total.
data: MaybeUninit<[T; N]>,
// The constant `N` parameter (and thus the total span of `data`) represent capacity for us,
// while the field below represents, as its name suggests, the current length of a StaticVec
// (that is, the current number of "live" elements) just as is the case for a regular `Vec`.
length: usize,
}
impl<T, const N: usize> StaticVec<T, N> {
/// Returns a new StaticVec instance.
///
/// # Example usage:
/// ```
/// # use staticvec::StaticVec;
/// let v = StaticVec::<i32, 4>::new();
/// assert_eq!(v.len(), 0);
/// assert_eq!(v.capacity(), 4);
/// static CV: StaticVec<i32, 4> = StaticVec::new();
/// static LEN: usize = CV.len();
/// static CAP: usize = CV.capacity();
/// assert_eq!(LEN, 0);
/// assert_eq!(CAP, 4);
/// ```
#[inline(always)]
pub const fn new() -> Self {
Self {
data: Self::new_data_uninit(),
length: 0,
}
}
/// Returns a new StaticVec instance filled with the contents, if any, of a slice reference,
/// which can be either `&mut` or `&` as if it is `&mut` it will implicitly coerce to `&`.
/// If the slice has a length greater than the StaticVec's declared capacity,
/// any contents after that point are ignored.
/// Locally requires that `T` implements [`Copy`](core::marker::Copy) to avoid soundness issues.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let v = StaticVec::<i32, 8>::new_from_slice(&[1, 2, 3]);
/// assert_eq!(v, [1, 2, 3]);
/// ```
#[inline]
pub const fn new_from_slice(values: &[T]) -> Self
where T: Copy {
let length = const_min(values.len(), N);
Self {
data: {
let mut data = Self::new_data_uninit();
unsafe {
values
.as_ptr()
.copy_to_nonoverlapping(Self::first_ptr_mut(&mut data), length);
data
}
},
length,
}
}
/// Returns a new StaticVec instance filled with the contents, if any, of an array.
/// If the array has a length greater than the StaticVec's declared capacity,
/// any contents after that point are ignored.
///
/// The `N2` parameter does not need to be provided explicitly, and can be inferred from the array
/// itself.
///
/// This function does *not* leak memory, as any ignored extra elements in the source
/// array are explicitly dropped with [`drop_in_place`](core::ptr::drop_in_place) after it is
/// first wrapped in an instance of [`MaybeUninit`](core::mem::MaybeUninit) to inhibit the
/// automatic calling of any destructors its contents may have.
///
/// # Example usage:
/// ```
/// # use staticvec::StaticVec;
/// // Same input length as the declared capacity:
/// let v = StaticVec::<i32, 3>::new_from_array([1, 2, 3]);
/// assert_eq!(v, [1, 2, 3]);
/// // Truncated to fit the declared capacity:
/// let v2 = StaticVec::<i32, 3>::new_from_array([1, 2, 3, 4, 5, 6]);
/// assert_eq!(v2, [1, 2, 3]);
/// ```
/// Note that StaticVec also implements [`From`](core::convert::From) for both slices and static
/// arrays (as well as several other types), which may prove more ergonomic in some cases as it
/// allows for a greater degree of type inference:
/// ```
/// # use staticvec::StaticVec;
/// // The StaticVec on the next line is inferred to be of type `StaticVec<&'static str, 4>`.
/// let v = StaticVec::from(["A", "B", "C", "D"]);
/// ```
#[inline]
pub fn new_from_array<const N2: usize>(values: [T; N2]) -> Self {
if N == N2 {
Self::from(values)
} else {
Self {
data: {
unsafe {
let mut data = Self::new_data_uninit();
values
.as_ptr()
.copy_to_nonoverlapping(Self::first_ptr_mut(&mut data), N2.min(N));
// Wrap the values in a MaybeUninit to inhibit their destructors (if any),
// then manually drop any excess ones. From the assembly output I've looked
// at, the compiler interprets this whole sequence in a way that doesn't result
// in any excess copying, so there should be no performance concerns for larger
// input arrays.
let mut forgotten = MaybeUninit::new(values);
ptr::drop_in_place(forgotten.assume_init_mut().get_unchecked_mut(N2.min(N)..N2));
data
}
},
length: N2.min(N),
}
}
}
/// A version of [`new_from_array`](crate::StaticVec::new_from_array) specifically designed
/// for use as a `const fn` constructor (although it can of course be used in non-const contexts
/// as well.)
///
/// Being `const` necessitates that this function can only accept arrays with a length
/// exactly equal to the declared capacity of the resulting StaticVec, so if you do need
/// flexibility with regards to input lengths it's recommended that you use
/// [`new_from_array`](crate::StaticVec::new_from_array) or the [`From`](core::convert::From)
/// implementations instead.
///
/// Note that both forms of the [`staticvec!`] macro are implemented using
/// [`new_from_const_array`](crate::StaticVec::new_from_const_array), so you may also prefer
/// to use them instead of it directly.
///
/// # Example usage:
/// ```
/// # use staticvec::{staticvec, StaticVec};
/// const v: StaticVec<i32, 4> = StaticVec::new_from_const_array([1, 2, 3, 4]);
/// assert_eq!(v, staticvec![1, 2, 3, 4]);
/// ```
#[inline(always)]
pub const fn new_from_const_array(values: [T; N]) -> Self {
Self {
data: MaybeUninit::new(values),
length: N,
}
}
/// Returns the current length of the StaticVec. Just as for a normal [`Vec`](alloc::vec::Vec),
/// this means the number of elements that have been added to it with
/// [`push`](crate::StaticVec::push), [`insert`](crate::StaticVec::insert), etc. except in the
/// case that it has been set directly with the unsafe [`set_len`](crate::StaticVec::set_len)
/// function.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert_eq!(staticvec![1].len(), 1);
/// ```
#[inline(always)]
pub const fn len(&self) -> usize {
self.length
}
/// Returns the total capacity of the StaticVec.
/// This is always equivalent to the generic `N` parameter it was declared with, which determines
/// the fixed size of the backing array.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert_eq!(StaticVec::<usize, 800>::new().capacity(), 800);
/// ```
#[inline(always)]
pub const fn capacity(&self) -> usize {
N
}
/// Does the same thing as [`capacity`](crate::StaticVec::capacity), but as an associated function
/// rather than a method.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert_eq!(StaticVec::<f64, 12>::cap(), 12)
/// ```
#[inline(always)]
pub const fn cap() -> usize {
N
}
/// Serves the same purpose as [`capacity`](crate::StaticVec::capacity), but as an associated
/// constant rather than a method.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert_eq!(StaticVec::<f64, 12>::CAPACITY, 12)
/// ```
pub const CAPACITY: usize = N;
/// Returns the remaining capacity (which is to say, `self.capacity() - self.len()`) of the
/// StaticVec.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut vec = StaticVec::<i32, 100>::new();
/// vec.push(1);
/// assert_eq!(vec.remaining_capacity(), 99);
/// ```
#[inline(always)]
pub const fn remaining_capacity(&self) -> usize {
N - self.length
}
/// Returns the total size of the inhabited part of the StaticVec (which may be zero if it has a
/// length of zero or contains ZSTs) in bytes. Specifically, the return value of this function
/// amounts to a calculation of `size_of::<T>() * self.len()`.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let x = StaticVec::<u8, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
/// assert_eq!(x.size_in_bytes(), 8);
/// let y = StaticVec::<u16, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
/// assert_eq!(y.size_in_bytes(), 16);
/// let z = StaticVec::<u32, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
/// assert_eq!(z.size_in_bytes(), 32);
/// let w = StaticVec::<u64, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
/// assert_eq!(w.size_in_bytes(), 64);
/// ```
#[inline(always)]
pub const fn size_in_bytes(&self) -> usize {
size_of::<T>() * self.length
}
/// Directly sets the length field of the StaticVec to `new_len`. Useful if you intend
/// to write to it solely element-wise, but marked unsafe due to how it creates
/// the potential for reading from uninitialized memory later on.
///
/// # Safety
///
/// It is up to the caller to ensure that `new_len` is less than or equal to the StaticVec's
/// constant `N` parameter, and that the range of elements covered by a length of `new_len` is
/// actually initialized. Failure to do so will almost certainly result in undefined behavior.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut vec = StaticVec::<i32, 12>::new();
/// let data = staticvec![1, 2, 3, 4];
/// unsafe {
/// data.as_ptr().copy_to_nonoverlapping(vec.as_mut_ptr(), 4);
/// vec.set_len(4);
/// }
/// assert_eq!(vec.len(), 4);
/// assert_eq!(vec.remaining_capacity(), 8);
/// assert_eq!(vec, data);
/// ```
#[inline(always)]
pub const unsafe fn set_len(&mut self, new_len: usize) {
// Most of the `unsafe` functions in this crate that are heavily used internally
// have debug-build-only assertions where it's useful.
/*
// The formatted assertion macros are not const-compatible yet.
debug_assert!(
new_len <= N,
"In `StaticVec::set_len`, provided length {} exceeds the maximum capacity of {}!",
new_len,
N
);
*/
debug_assert!(
new_len <= N,
"A `new_len` greater than `N` was passed to `StaticVec::set_len`!"
);
self.length = new_len;
}
/// Returns true if the current length of the StaticVec is 0.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert!(StaticVec::<i32, 4>::new().is_empty());
/// ```
#[inline(always)]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
/// Returns true if the current length of the StaticVec is greater than 0.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert!(staticvec![staticvec![1, 1], staticvec![2, 2]].is_not_empty());
/// ```
// Clippy wants `!is_empty()` for this, but I prefer it as-is. My question is though, does it
// actually know that we have an applicable `is_empty()` function, or is it just guessing? I'm not
// sure.
#[allow(clippy::len_zero)]
#[inline(always)]
pub const fn is_not_empty(&self) -> bool {
self.length > 0
}
/// Returns true if the current length of the StaticVec is equal to its capacity.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert!(StaticVec::<i32, 4>::filled_with(|| 2).is_full());
/// ```
#[inline(always)]
pub const fn is_full(&self) -> bool {
self.length == N
}
/// Returns true if the current length of the StaticVec is less than its capacity.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert!(StaticVec::<i32, 4>::new().is_not_full());
/// ```
#[inline(always)]
pub const fn is_not_full(&self) -> bool {
self.length < N
}
/// Returns a constant pointer to the first element of the StaticVec's internal array.
/// It is up to the caller to ensure that the StaticVec lives for as long as they intend
/// to make use of the returned pointer, as once the StaticVec is dropped the pointer will
/// point to uninitialized or "garbage" memory.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let v = staticvec!['A', 'B', 'C'];
/// let p = v.as_ptr();
/// unsafe { assert_eq!(*p, 'A') };
/// ```
#[inline(always)]
pub const fn as_ptr(&self) -> *const T {
Self::first_ptr(&self.data)
}
/// Returns a mutable pointer to the first element of the StaticVec's internal array.
/// It is up to the caller to ensure that the StaticVec lives for as long as they intend
/// to make use of the returned pointer, as once the StaticVec is dropped the pointer will
/// point to uninitialized or "garbage" memory.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = staticvec!['A', 'B', 'C'];
/// let p = v.as_mut_ptr();
/// unsafe { *p = 'X' };
/// assert_eq!(v, ['X', 'B', 'C']);
/// ```
#[inline(always)]
pub const fn as_mut_ptr(&mut self) -> *mut T {
Self::first_ptr_mut(&mut self.data)
}
/// Returns a constant reference to a slice of the StaticVec's inhabited area.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert_eq!(staticvec![1, 2, 3].as_slice(), &[1, 2, 3]);
/// ```
#[inline(always)]
pub const fn as_slice(&self) -> &[T] {
// Safety: `self.as_ptr()` is a pointer to an array for which the first `length`
// elements are guaranteed to be initialized. Therefore this is a valid slice.
slice_from_raw_parts(self.as_ptr(), self.length)
}
/// Returns a mutable reference to a slice of the StaticVec's inhabited area.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = staticvec![4, 5, 6];
/// let s = v.as_mut_slice();
/// s[1] = 9;
/// assert_eq!(v, [4, 9, 6]);
/// ```
#[inline(always)]
pub const fn as_mut_slice(&mut self) -> &mut [T] {
// Safety: See as_slice.
slice_from_raw_parts_mut(self.as_mut_ptr(), self.length)
}
/// Returns a constant pointer to the element of the StaticVec at `index` without doing any
/// checking to ensure that `index` is actually within any particular bounds. The return value of
/// this function is equivalent to what would be returned from `as_ptr().add(index)`.
///
/// # Safety
///
/// It is up to the caller to ensure that `index` is within the appropriate bounds such that the
/// function returns a pointer to a location that falls somewhere inside the full span of the
/// StaticVec's backing array, and that if reading from the returned pointer, it has *already*
/// been initialized properly.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let v = staticvec!["I", "am", "a", "StaticVec!"];
/// unsafe {
/// let p = v.ptr_at_unchecked(3);
/// assert_eq!(*p, "StaticVec!");
/// }
/// ```
#[inline(always)]
pub const unsafe fn ptr_at_unchecked(&self, index: usize) -> *const T {
// We (inclusively, to account for the possibility of `N` being 0) check against `N` as opposed
// to `length` in our debug assertion here, as these `_unchecked` versions of `ptr_at` and
// `mut_ptr_at` are primarily intended for initialization-related purposes (and used extensively
// that way internally throughout the crate.)
/*
// The formatted assertion macros are not const-compatible yet.
debug_assert!(
index <= N,
"In `StaticVec::ptr_at_unchecked`, provided index {} must be within `0..={}`!",
index,
N
);
*/
debug_assert!(
index <= N,
"Bounds check failure in `StaticVec::ptr_at_unchecked`!",
);
// Safety: `index` is explicitly a `usize` to start with, and so cannot be negative at this
// point.
self.as_ptr().add(index)
}
/// Returns a mutable pointer to the element of the StaticVec at `index` without doing any
/// checking to ensure that `index` is actually within any particular bounds. The return value of
/// this function is equivalent to what would be returned from `as_mut_ptr().add(index)`.
///
/// # Safety
///
/// It is up to the caller to ensure that `index` is within the appropriate bounds such that the
/// function returns a pointer to a location that falls somewhere inside the full span of the
/// StaticVec's backing array.
///
/// It is also the responsibility of the caller to ensure that the `length` field of the StaticVec
/// is adjusted to properly reflect whatever range of elements this function may be used to
/// initialize, and that if reading from the returned pointer, it has *already* been initialized
/// properly.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = staticvec!["I", "am", "not a", "StaticVec!"];
/// unsafe {
/// let p = v.mut_ptr_at_unchecked(2);
/// *p = "a";
/// }
/// assert_eq!(v, ["I", "am", "a", "StaticVec!"]);
/// ```
#[inline(always)]
pub const unsafe fn mut_ptr_at_unchecked(&mut self, index: usize) -> *mut T {
// We (inclusively, to account for the possibility of `N` being 0) check against `N` as opposed
// to `length` in our debug assertion here, as these `_unchecked` versions of `ptr_at` and
// `mut_ptr_at` are primarily intended for initialization-related purposes (and used extensively
// that way internally throughout the crate.)
/*
// The formatted assertion macros are not const-compatible yet.
debug_assert!(
index <= N,
"In `StaticVec::mut_ptr_at_unchecked`, provided index {} must be within `0..={}`!",
index,
N
);
*/
debug_assert!(
index <= N,
"Bounds check failure in `StaticVec::mut_ptr_at_unchecked`!",
);
// Safety: `index` is explicitly a `usize` to start with, and so cannot be negative at this
// point.
self.as_mut_ptr().add(index)
}
/// Returns a constant pointer to the element of the StaticVec at `index` if `index`
/// is within the range `0..self.length`, or panics if it is not. The return value of this
/// function is equivalent to what would be returned from `as_ptr().add(index)`.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let v = staticvec!["I", "am", "a", "StaticVec!"];
/// let p = v.ptr_at(3);
/// unsafe { assert_eq!(*p, "StaticVec!") };
/// ```
#[inline(always)]
pub const fn ptr_at(&self, index: usize) -> *const T {
/*
// The formatted assertion macros are not const-compatible yet.
assert!(
index < self.length,
"In `StaticVec::ptr_at`, provided index {} must be within `0..{}`!",
index,
self.length
);
*/
assert!(
index < self.length,
"Bounds check failure in `StaticVec::ptr_at`!"
);
unsafe { self.ptr_at_unchecked(index) }
}
/// Returns a mutable pointer to the element of the StaticVec at `index` if `index`
/// is within the range `0..self.length`, or panics if it is not. The return value of this
/// function is equivalent to what would be returned from `as_mut_ptr().add(index)`.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = staticvec!["I", "am", "not a", "StaticVec!"];
/// let p = v.mut_ptr_at(2);
/// unsafe { *p = "a" };
/// assert_eq!(v, ["I", "am", "a", "StaticVec!"]);
/// ```
#[inline(always)]
pub const fn mut_ptr_at(&mut self, index: usize) -> *mut T {
/*
// The formatted assertion macros are not const-compatible yet.
assert!(
index < self.length,
"In `StaticVec::mut_ptr_at`, provided index {} must be within `0..{}`!",
index,
self.length
);
*/
assert!(
index < self.length,
"Bounds check failure in `StaticVec::mut_ptr_at`!"
);
unsafe { self.mut_ptr_at_unchecked(index) }
}
/// Returns a constant reference to the element of the StaticVec at `index` without doing any
/// checking to ensure that `index` is actually within any particular bounds.
///
/// Note that unlike [`slice::get_unchecked`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.get_unchecked),
/// this method only supports accessing individual elements via `usize`; it cannot also produce
/// subslices. To get a subslice without a bounds check, use
/// `self.as_slice().get_unchecked(a..b)`.
///
/// # Safety
///
/// It is up to the caller to ensure that `index` is within the range `0..self.length`.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// unsafe { assert_eq!(*staticvec![1, 2, 3].get_unchecked(1), 2) };
/// ```
#[inline(always)]
pub const unsafe fn get_unchecked(&self, index: usize) -> &T {
// This function is used internally in places where `length` has been intentionally
// temporarily set to zero, so we do our debug assertion against `N`.
/*
// The formatted assertion macros are not const-compatible yet.
debug_assert!(
index < N,
"In `StaticVec::get_unchecked`, provided index {} must be within `0..{}`!",
index,
N
);
*/
debug_assert!(
index < N,
"Bounds check failure in `StaticVec::get_unchecked`!"
);
&*self.ptr_at_unchecked(index)
}
/// Returns a mutable reference to the element of the StaticVec at `index` without doing any
/// checking to ensure that `index` is actually within any particular bounds.
///
/// The same differences between this method and the slice method of the same name
/// apply as do for [`get_unchecked`](crate::StaticVec::get_unchecked).
///
/// # Safety
///
/// It is up to the caller to ensure that `index` is within the range `0..self.length`.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = staticvec![1, 2, 3];
/// let p = unsafe { v.get_unchecked_mut(1) };
/// *p = 9;
/// assert_eq!(v, [1, 9, 3]);
/// ```
#[inline(always)]
pub const unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
// This function is used internally in places where `length` has been intentionally
// temporarily set to zero, so we do our debug assertion against `N`.
/*
// The formatted assertion macros are not const-compatible yet.
debug_assert!(
index < N,
"In `StaticVec::get_unchecked_mut`, provided index {} must be within `0..{}`!",
index,
N
);
*/
debug_assert!(
index < N,
"Bounds check failure in `StaticVec::get_unchecked_mut`!"
);
&mut *self.mut_ptr_at_unchecked(index)
}
/// Appends a value to the end of the StaticVec without asserting that
/// its current length is less than `N`.
///
/// # Safety
///
/// It is up to the caller to ensure that the length of the StaticVec
/// prior to using this function is less than `N`. Failure to do so will result
/// in writing to an out-of-bounds memory region.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = StaticVec::<i32, 4>::from([1, 2]);
/// unsafe { v.push_unchecked(3) };
/// assert_eq!(v, [1, 2, 3]);
/// ```
#[inline(always)]
pub const unsafe fn push_unchecked(&mut self, value: T) {
debug_assert!(
self.is_not_full(),
"`StaticVec::push_unchecked` was called through a StaticVec already at maximum capacity!"
);
let length = self.length;
self.mut_ptr_at_unchecked(length).write(value);
self.set_len(length + 1);
}
/// Pops a value from the end of the StaticVec and returns it directly without asserting that
/// the StaticVec's current length is greater than 0.
///
/// # Safety
///
/// It is up to the caller to ensure that the StaticVec contains at least one
/// element prior to using this function. Failure to do so will result in reading
/// from uninitialized memory.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = StaticVec::<i32, 4>::from([1, 2, 3, 4]);
/// unsafe { v.pop_unchecked() };
/// assert_eq!(v, [1, 2, 3]);
/// ```
#[inline(always)]
pub const unsafe fn pop_unchecked(&mut self) -> T {
debug_assert!(
self.is_not_empty(),
"`StaticVec::pop_unchecked` was called through an empty StaticVec!"
);
let new_length = self.length - 1;
self.set_len(new_length);
self.ptr_at_unchecked(new_length).read()
}
/// Pushes `value` to the StaticVec if its current length is less than its capacity,
/// or returns a [`PushCapacityError`](crate::errors::PushCapacityError) otherwise.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v1 = StaticVec::<usize, 128>::filled_with_by_index(|i| i * 4);
/// assert!(v1.try_push(999).is_err());
/// let mut v2 = StaticVec::<usize, 128>::new();
/// assert!(v2.try_push(1).is_ok());
/// ```
#[inline(always)]
pub const fn try_push(&mut self, value: T) -> Result<(), PushCapacityError<T, N>> {
if self.is_not_full() {
unsafe { self.push_unchecked(value) };
Ok(())
} else {
Err(PushCapacityError::new(value))
}
}
/// Pushes a value to the end of the StaticVec. Panics if the collection is
/// full; that is, if `self.len() == self.capacity()`.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = StaticVec::<i32, 8>::new();
/// v.push(1);
/// v.push(2);
/// assert_eq!(v, [1, 2]);
/// ```
#[inline(always)]
pub const fn push(&mut self, value: T) {
assert!(
self.is_not_full(),
"`StaticVec::push` was called through a StaticVec already at maximum capacity!"
);
unsafe { self.push_unchecked(value) };
}
/// Removes the value at the last position of the StaticVec and returns it in `Some` if
/// the StaticVec has a current length greater than 0, and returns `None` otherwise.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut v = staticvec![1, 2, 3, 4];
/// assert_eq!(v.pop(), Some(4));
/// assert_eq!(v.pop(), Some(3));
/// assert_eq!(v, [1, 2]);
/// ```
#[inline(always)]
pub const fn pop(&mut self) -> Option<T> {
if self.is_empty() {
None
} else {
Some(unsafe { self.pop_unchecked() })
}
}
/// Returns a constant reference to the first element of the StaticVec in `Some` if the StaticVec
/// is not empty, or `None` otherwise.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let v1 = staticvec![10, 40, 30];
/// assert_eq!(Some(&10), v1.first());
/// let v2 = StaticVec::<i32, 0>::new();
/// assert_eq!(None, v2.first());
/// ```
#[inline(always)]
pub const fn first(&self) -> Option<&T> {
if self.is_empty() {
None
} else {
Some(unsafe { self.get_unchecked(0) })
}
}
/// Returns a mutable reference to the first element of the StaticVec in `Some` if the StaticVec
/// is not empty, or `None` otherwise.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut x = staticvec![0, 1, 2];
/// if let Some(first) = x.first_mut() {
/// *first = 5;
/// }
/// assert_eq!(x, &[5, 1, 2]);
/// ```
#[inline(always)]
pub const fn first_mut(&mut self) -> Option<&mut T> {
if self.is_empty() {
None
} else {
Some(unsafe { self.get_unchecked_mut(0) })
}
}
/// Returns a constant reference to the last element of the StaticVec in `Some` if the StaticVec
/// is not empty, or `None` otherwise.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let v = staticvec![10, 40, 30];
/// assert_eq!(Some(&30), v.last());
/// let w = StaticVec::<i32, 0>::new();
/// assert_eq!(None, w.last());
/// ```
#[inline(always)]
pub const fn last(&self) -> Option<&T> {
if self.is_empty() {
None
} else {
Some(unsafe { self.get_unchecked(self.length - 1) })
}
}
/// Returns a mutable reference to the last element of the StaticVec in `Some` if the StaticVec is
/// not empty, or `None` otherwise.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// let mut x = staticvec![0, 1, 2];
/// if let Some(last) = x.last_mut() {
/// *last = 10;
/// }
/// assert_eq!(x, &[0, 1, 10]);
/// ```
#[inline(always)]
pub const fn last_mut(&mut self) -> Option<&mut T> {
if self.is_empty() {
None
} else {
Some(unsafe { self.get_unchecked_mut(self.length - 1) })
}
}
/// A crate-local unchecked version of `remove`, currently only used in the implementation of
/// `StaticVecSplice`.
#[inline]
pub(crate) const fn remove_unchecked(&mut self, index: usize) -> T {
let old_length = self.length;
unsafe {
let self_ptr = self.mut_ptr_at_unchecked(index);
let res = self_ptr.read();
self_ptr.offset(1).copy_to(self_ptr, old_length - index - 1);
self.set_len(old_length - 1);
res
}
}
/// Asserts that `index` is less than the current length of the StaticVec,
/// and if so removes the value at that position and returns it. Any values
/// that exist in later positions are shifted to the left.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert_eq!(staticvec![1, 2, 3].remove(1), 2);
/// ```
#[inline]
pub const fn remove(&mut self, index: usize) -> T {
let old_length = self.length;
assert!(
index < old_length,
"Bounds check failure in `StaticVec::remove`!"
);
unsafe {
let self_ptr = self.mut_ptr_at_unchecked(index);
let res = self_ptr.read();
self_ptr.offset(1).copy_to(self_ptr, old_length - index - 1);
self.set_len(old_length - 1);
res
}
}
/// Removes the first instance of `item` from the StaticVec if the item exists.
///
/// # Example usage:
/// ```
/// # use staticvec::*;
/// assert_eq!(staticvec![1, 2, 2, 3].remove_item(&2), Some(2));
/// ```
#[allow(clippy::manual_map)]
#[inline(always)]
pub fn remove_item(&mut self, item: &T) -> Option<T>
where T: PartialEq {
// Adapted this from normal Vec's implementation.
if let Some(pos) = self.iter().position(|x| *x == *item) {
Some(self.remove(pos))
} else {
None
}
}