-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathlib.rs
More file actions
4293 lines (3820 loc) · 131 KB
/
lib.rs
File metadata and controls
4293 lines (3820 loc) · 131 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
#![deny(missing_docs)]
//! `ThinVec` is exactly the same as `Vec`, except that it stores its `len` and `capacity` in the buffer
//! it allocates.
//!
//! This makes the memory footprint of ThinVecs lower; notably in cases where space is reserved for
//! a non-existence `ThinVec<T>`. So `Vec<ThinVec<T>>` and `Option<ThinVec<T>>::None` will waste less
//! space. Being pointer-sized also means it can be passed/stored in registers.
//!
//! Of course, any actually constructed `ThinVec` will theoretically have a bigger allocation, but
//! the fuzzy nature of allocators means that might not actually be the case.
//!
//! Properties of `Vec` that are preserved:
//! * `ThinVec::new()` doesn't allocate (it points to a statically allocated singleton)
//! * reallocation can be done in place
//! * `size_of::<ThinVec<T>>()` == `size_of::<Option<ThinVec<T>>>()`
//!
//! Properties of `Vec` that aren't preserved:
//! * `ThinVec<T>` can't ever be zero-cost roundtripped to a `Box<[T]>`, `String`, or `*mut T`
//! * `from_raw_parts` doesn't exist
//! * `ThinVec` currently doesn't bother to not-allocate for Zero Sized Types (e.g. `ThinVec<()>`),
//! but it could be done if someone cared enough to implement it.
//!
//!
//!
//! # Gecko FFI
//!
//! If you enable the gecko-ffi feature, `ThinVec` will verbatim bridge with the nsTArray type in
//! Gecko (Firefox). That is, `ThinVec` and nsTArray have identical layouts *but not ABIs*,
//! so nsTArrays/ThinVecs an be natively manipulated by C++ and Rust, and ownership can be
//! transferred across the FFI boundary (**IF YOU ARE CAREFUL, SEE BELOW!!**).
//!
//! While this feature is handy, it is also inherently dangerous to use because Rust and C++ do not
//! know about each other. Specifically, this can be an issue with non-POD types (types which
//! have destructors, move constructors, or are `!Copy`).
//!
//! ## Do Not Pass By Value
//!
//! The biggest thing to keep in mind is that **FFI functions cannot pass ThinVec/nsTArray
//! by-value**. That is, these are busted APIs:
//!
//! ```rust,ignore
//! // BAD WRONG
//! extern fn process_data(data: ThinVec<u32>) { ... }
//! // BAD WRONG
//! extern fn get_data() -> ThinVec<u32> { ... }
//! ```
//!
//! You must instead pass by-reference:
//!
//! ```rust
//! # use thin_vec::*;
//! # use std::mem;
//!
//! // Read-only access, ok!
//! extern fn process_data(data: &ThinVec<u32>) {
//! for val in data {
//! println!("{}", val);
//! }
//! }
//!
//! // Replace with empty instance to take ownership, ok!
//! extern fn consume_data(data: &mut ThinVec<u32>) {
//! let owned = mem::replace(data, ThinVec::new());
//! mem::drop(owned);
//! }
//!
//! // Mutate input, ok!
//! extern fn add_data(dataset: &mut ThinVec<u32>) {
//! dataset.push(37);
//! dataset.push(12);
//! }
//!
//! // Return via out-param, usually ok!
//! //
//! // WARNING: output must be initialized! (Empty nsTArrays are free, so just do it!)
//! extern fn get_data(output: &mut ThinVec<u32>) {
//! *output = thin_vec![1, 2, 3, 4, 5];
//! }
//! ```
//!
//! Ignorable Explanation For Those Who Really Want To Know Why:
//!
//! > The fundamental issue is that Rust and C++ can't currently communicate about destructors, and
//! > the semantics of C++ require destructors of function arguments to be run when the function
//! > returns. Whether the callee or caller is responsible for this is also platform-specific, so
//! > trying to hack around it manually would be messy.
//! >
//! > Also a type having a destructor changes its C++ ABI, because that type must actually exist
//! > in memory (unlike a trivial struct, which is often passed in registers). We don't currently
//! > have a way to communicate to Rust that this is happening, so even if we worked out the
//! > destructor issue with say, MaybeUninit, it would still be a non-starter without some RFCs
//! > to add explicit rustc support.
//! >
//! > Realistically, the best answer here is to have a "heavier" bindgen that can secretly
//! > generate FFI glue so we can pass things "by value" and have it generate by-reference code
//! > behind our back (like the cxx crate does). This would muddy up debugging/searchfox though.
//!
//! ## Types Should Be Trivially Relocatable
//!
//! Types in Rust are always trivially relocatable (unless suitably borrowed/[pinned][]/hidden).
//! This means all Rust types are legal to relocate with a bitwise copy, you cannot provide
//! copy or move constructors to execute when this happens, and the old location won't have its
//! destructor run. This will cause problems for types which have a significant location
//! (types that intrusively point into themselves or have their location registered with a service).
//!
//! While relocations are generally predictable if you're very careful, **you should avoid using
//! types with significant locations with Rust FFI**.
//!
//! Specifically, `ThinVec` will trivially relocate its contents whenever it needs to reallocate its
//! buffer to change its capacity. This is the default reallocation strategy for nsTArray, and is
//! suitable for the vast majority of types. Just be aware of this limitation!
//!
//! ## Auto Arrays Are Dangerous
//!
//! `ThinVec` has *some* support for handling auto arrays which store their buffer on the stack,
//! but this isn't well tested.
//!
//! Regardless of how much support we provide, Rust won't be aware of the buffer's limited lifetime,
//! so standard auto array safety caveats apply about returning/storing them! `ThinVec` won't ever
//! produce an auto array on its own, so this is only an issue for transferring an nsTArray into
//! Rust.
//!
//! ## Other Issues
//!
//! Standard FFI caveats also apply:
//!
//! * Rust is more strict about POD types being initialized (use MaybeUninit if you must)
//! * `ThinVec<T>` has no idea if the C++ version of `T` has move/copy/assign/delete overloads
//! * `nsTArray<T>` has no idea if the Rust version of `T` has a Drop/Clone impl
//! * C++ can do all sorts of unsound things that Rust can't catch
//! * C++ and Rust don't agree on how zero-sized/empty types should be handled
//!
//! The gecko-ffi feature will not work if you aren't linking with code that has nsTArray
//! defined. Specifically, we must share the symbol for nsTArray's empty singleton. You will get
//! linking errors if that isn't defined.
//!
//! The gecko-ffi feature also limits `ThinVec` to the legacy behaviors of nsTArray. Most notably,
//! nsTArray has a maximum capacity of i32::MAX (~2.1 billion items). Probably not an issue.
//! Probably.
//!
//! [pinned]: https://doc.rust-lang.org/std/pin/index.html
#![allow(clippy::comparison_chain, clippy::missing_safety_doc)]
use std::alloc::*;
use std::borrow::*;
use std::cmp::*;
use std::convert::TryFrom;
use std::convert::TryInto;
use std::hash::*;
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::ops::Bound;
use std::ops::{Deref, DerefMut, RangeBounds};
use std::ptr::NonNull;
use std::slice::IterMut;
use std::{fmt, io, mem, ptr, slice};
use impl_details::*;
// modules: a simple way to cfg a whole bunch of impl details at once
#[cfg(not(feature = "gecko-ffi"))]
mod impl_details {
pub type SizeType = usize;
pub const MAX_CAP: usize = !0;
#[inline(always)]
pub fn assert_size(x: usize) -> SizeType {
x
}
}
#[cfg(feature = "gecko-ffi")]
mod impl_details {
// Support for briding a gecko nsTArray verbatim into a ThinVec.
//
// `ThinVec` can't see copy/move/delete implementations
// from C++
//
// The actual layout of an nsTArray is:
//
// ```cpp
// struct {
// uint32_t mLength;
// uint32_t mCapacity: 31;
// uint32_t mIsAutoArray: 1;
// }
// ```
//
// Rust doesn't natively support bit-fields, so we manually mask
// and shift the bit. When the "auto" bit is set, the header and buffer
// are actually on the stack, meaning the `ThinVec` pointer-to-header
// is essentially an "owned borrow", and therefore dangerous to handle.
// There are no safety guards for this situation.
//
// On little-endian platforms, the auto bit will be the high-bit of
// our capacity u32. On big-endian platforms, it will be the low bit.
// Hence we need some platform-specific CFGs for the necessary masking/shifting.
//
// `ThinVec` won't ever construct an auto array. They only happen when
// bridging from C++. This means we don't need to ever set/preserve the bit.
// We just need to be able to read and handle it if it happens to be there.
//
// Handling the auto bit mostly just means not freeing/reallocating the buffer.
pub type SizeType = u32;
pub const MAX_CAP: usize = i32::max_value() as usize;
// Little endian: the auto bit is the high bit, and the capacity is
// verbatim. So we just need to mask off the high bit. Note that
// this masking is unnecessary when packing, because assert_size
// guards against the high bit being set.
#[cfg(target_endian = "little")]
pub fn pack_capacity(cap: SizeType) -> SizeType {
cap as SizeType
}
#[cfg(target_endian = "little")]
pub fn unpack_capacity(cap: SizeType) -> usize {
(cap as usize) & !(1 << 31)
}
#[cfg(target_endian = "little")]
pub fn is_auto(cap: SizeType) -> bool {
(cap & (1 << 31)) != 0
}
// Big endian: the auto bit is the low bit, and the capacity is
// shifted up one bit. Masking out the auto bit is unnecessary,
// as rust shifts always shift in 0's for unsigned integers.
#[cfg(target_endian = "big")]
pub fn pack_capacity(cap: SizeType) -> SizeType {
(cap as SizeType) << 1
}
#[cfg(target_endian = "big")]
pub fn unpack_capacity(cap: SizeType) -> usize {
(cap >> 1) as usize
}
#[cfg(target_endian = "big")]
pub fn is_auto(cap: SizeType) -> bool {
(cap & 1) != 0
}
#[inline]
pub fn assert_size(x: usize) -> SizeType {
if x > MAX_CAP as usize {
panic!("nsTArray size may not exceed the capacity of a 32-bit sized int");
}
x as SizeType
}
}
// The header of a ThinVec.
//
// The _cap can be a bitfield, so use accessors to avoid trouble.
//
// In "real" gecko-ffi mode, the empty singleton will be aligned
// to 8 by gecko. But in tests we have to provide the singleton
// ourselves, and Rust makes it hard to "just" align a static.
// To avoid messing around with a wrapper type around the
// singleton *just* for tests, we just force all headers to be
// aligned to 8 in this weird "zombie" gecko mode.
//
// This shouldn't affect runtime layout (padding), but it will
// result in us asking the allocator to needlessly overalign
// non-empty ThinVecs containing align < 8 types in
// zombie-mode, but not in "real" geck-ffi mode. Minor.
#[cfg_attr(all(feature = "gecko-ffi", any(test, miri)), repr(align(8)))]
#[repr(C)]
struct Header {
_len: SizeType,
_cap: SizeType,
}
impl Header {
#[inline]
#[allow(clippy::unnecessary_cast)]
fn len(&self) -> usize {
self._len as usize
}
#[inline]
fn set_len(&mut self, len: usize) {
self._len = assert_size(len);
}
}
#[cfg(feature = "gecko-ffi")]
impl Header {
fn cap(&self) -> usize {
unpack_capacity(self._cap)
}
fn set_cap(&mut self, cap: usize) {
// debug check that our packing is working
debug_assert_eq!(unpack_capacity(pack_capacity(cap as SizeType)), cap);
// FIXME: this assert is busted because it reads uninit memory
// debug_assert!(!self.uses_stack_allocated_buffer());
// NOTE: this always stores a cleared auto bit, because set_cap
// is only invoked by Rust, and Rust doesn't create auto arrays.
self._cap = pack_capacity(assert_size(cap));
}
fn uses_stack_allocated_buffer(&self) -> bool {
is_auto(self._cap)
}
}
#[cfg(not(feature = "gecko-ffi"))]
impl Header {
#[allow(clippy::unnecessary_cast)]
fn cap(&self) -> usize {
self._cap as usize
}
fn set_cap(&mut self, cap: usize) {
self._cap = assert_size(cap);
}
}
/// Singleton that all empty collections share.
/// Note: can't store non-zero ZSTs, we allocate in that case. We could
/// optimize everything to not do that (basically, make ptr == len and branch
/// on size == 0 in every method), but it's a bunch of work for something that
/// doesn't matter much.
#[cfg(any(not(feature = "gecko-ffi"), test, miri))]
static EMPTY_HEADER: Header = Header { _len: 0, _cap: 0 };
#[cfg(all(feature = "gecko-ffi", not(test), not(miri)))]
extern "C" {
#[link_name = "sEmptyTArrayHeader"]
static EMPTY_HEADER: Header;
}
// Utils for computing layouts of allocations
/// Gets the size necessary to allocate a `ThinVec<T>` with the give capacity.
///
/// # Panics
///
/// This will panic if isize::MAX is overflowed at any point.
fn alloc_size<T>(cap: usize) -> usize {
// Compute "real" header size with pointer math
//
// We turn everything into isizes here so that we can catch isize::MAX overflow,
// we never want to allow allocations larger than that!
let header_size = mem::size_of::<Header>() as isize;
let padding = padding::<T>() as isize;
let data_size = if mem::size_of::<T>() == 0 {
// If we're allocating an array for ZSTs we need a header/padding but no actual
// space for items, so we don't care about the capacity that was requested!
0
} else {
let cap: isize = cap.try_into().expect("capacity overflow");
let elem_size = mem::size_of::<T>() as isize;
elem_size.checked_mul(cap).expect("capacity overflow")
};
let final_size = data_size
.checked_add(header_size + padding)
.expect("capacity overflow");
// Ok now we can turn it back into a usize (don't need to worry about negatives)
final_size as usize
}
/// Gets the padding necessary for the array of a `ThinVec<T>`
fn padding<T>() -> usize {
let alloc_align = alloc_align::<T>();
let header_size = mem::size_of::<Header>();
if alloc_align > header_size {
if cfg!(feature = "gecko-ffi") {
panic!(
"nsTArray does not handle alignment above > {} correctly",
header_size
);
}
alloc_align - header_size
} else {
0
}
}
/// Gets the align necessary to allocate a `ThinVec<T>`
fn alloc_align<T>() -> usize {
max(mem::align_of::<T>(), mem::align_of::<Header>())
}
/// Gets the layout necessary to allocate a `ThinVec<T>`
///
/// # Panics
///
/// Panics if the required size overflows `isize::MAX`.
fn layout<T>(cap: usize) -> Layout {
unsafe { Layout::from_size_align_unchecked(alloc_size::<T>(cap), alloc_align::<T>()) }
}
/// Allocates a header (and array) for a `ThinVec<T>` with the given capacity.
///
/// # Panics
///
/// Panics if the required size overflows `isize::MAX`.
fn header_with_capacity<T>(cap: usize) -> NonNull<Header> {
debug_assert!(cap > 0);
unsafe {
let layout = layout::<T>(cap);
let header = alloc(layout) as *mut Header;
if header.is_null() {
handle_alloc_error(layout)
}
// "Infinite" capacity for zero-sized types:
(*header).set_cap(if mem::size_of::<T>() == 0 {
MAX_CAP
} else {
cap
});
(*header).set_len(0);
NonNull::new_unchecked(header)
}
}
/// See the crate's top level documentation for a description of this type.
#[repr(C)]
pub struct ThinVec<T> {
ptr: NonNull<Header>,
boo: PhantomData<T>,
}
unsafe impl<T: Sync> Sync for ThinVec<T> {}
unsafe impl<T: Send> Send for ThinVec<T> {}
/// Creates a `ThinVec` containing the arguments.
///
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`.
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")]
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")]
/// #[macro_use] extern crate thin_vec;
///
/// fn main() {
/// let v = thin_vec![1, 2, 3];
/// assert_eq!(v.len(), 3);
/// assert_eq!(v[0], 1);
/// assert_eq!(v[1], 2);
/// assert_eq!(v[2], 3);
///
/// let v = thin_vec![1; 3];
/// assert_eq!(v, [1, 1, 1]);
/// }
/// ```
#[macro_export]
macro_rules! thin_vec {
(@UNIT $($t:tt)*) => (());
($elem:expr; $n:expr) => ({
let mut vec = $crate::ThinVec::new();
vec.resize($n, $elem);
vec
});
() => {$crate::ThinVec::new()};
($($x:expr),*) => ({
let len = [$(thin_vec!(@UNIT $x)),*].len();
let mut vec = $crate::ThinVec::with_capacity(len);
$(vec.push($x);)*
vec
});
($($x:expr,)*) => (thin_vec![$($x),*]);
}
impl<T> ThinVec<T> {
/// Creates a new empty ThinVec.
///
/// This will not allocate.
pub fn new() -> ThinVec<T> {
ThinVec::with_capacity(0)
}
/// Constructs a new, empty `ThinVec<T>` with at least the specified capacity.
///
/// The vector will be able to hold at least `capacity` elements without
/// reallocating. This method is allowed to allocate for more elements than
/// `capacity`. If `capacity` is 0, the vector will not allocate.
///
/// It is important to note that although the returned vector has the
/// minimum *capacity* specified, the vector will have a zero *length*.
///
/// If it is important to know the exact allocated capacity of a `ThinVec`,
/// always use the [`capacity`] method after construction.
///
/// **NOTE**: unlike `Vec`, `ThinVec` **MUST** allocate once to keep track of non-zero
/// lengths. As such, we cannot provide the same guarantees about ThinVecs
/// of ZSTs not allocating. However the allocation never needs to be resized
/// to add more ZSTs, since the underlying array is still length 0.
///
/// [Capacity and reallocation]: #capacity-and-reallocation
/// [`capacity`]: Vec::capacity
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` bytes.
///
/// # Examples
///
/// ```
/// use thin_vec::ThinVec;
///
/// let mut vec = ThinVec::with_capacity(10);
///
/// // The vector contains no items, even though it has capacity for more
/// assert_eq!(vec.len(), 0);
/// assert!(vec.capacity() >= 10);
///
/// // These are all done without reallocating...
/// for i in 0..10 {
/// vec.push(i);
/// }
/// assert_eq!(vec.len(), 10);
/// assert!(vec.capacity() >= 10);
///
/// // ...but this may make the vector reallocate
/// vec.push(11);
/// assert_eq!(vec.len(), 11);
/// assert!(vec.capacity() >= 11);
///
/// // A vector of a zero-sized type will always over-allocate, since no
/// // space is needed to store the actual elements.
/// let vec_units = ThinVec::<()>::with_capacity(10);
///
/// // Only true **without** the gecko-ffi feature!
/// // assert_eq!(vec_units.capacity(), usize::MAX);
/// ```
pub fn with_capacity(cap: usize) -> ThinVec<T> {
// `padding` contains ~static assertions against types that are
// incompatible with the current feature flags. We also call it to
// invoke these assertions when getting a pointer to the `ThinVec`
// contents, but since we also get a pointer to the contents in the
// `Drop` impl, trippng an assertion along that code path causes a
// double panic. We duplicate the assertion here so that it is
// testable,
let _ = padding::<T>();
if cap == 0 {
unsafe {
ThinVec {
ptr: NonNull::new_unchecked(&EMPTY_HEADER as *const Header as *mut Header),
boo: PhantomData,
}
}
} else {
ThinVec {
ptr: header_with_capacity::<T>(cap),
boo: PhantomData,
}
}
}
// Accessor conveniences
fn ptr(&self) -> *mut Header {
self.ptr.as_ptr()
}
fn header(&self) -> &Header {
unsafe { self.ptr.as_ref() }
}
fn data_raw(&self) -> *mut T {
// `padding` contains ~static assertions against types that are
// incompatible with the current feature flags. Even if we don't
// care about its result, we should always call it before getting
// a data pointer to guard against invalid types!
let padding = padding::<T>();
// Although we ensure the data array is aligned when we allocate,
// we can't do that with the empty singleton. So when it might not
// be properly aligned, we substitute in the NonNull::dangling
// which *is* aligned.
//
// To minimize dynamic branches on `cap` for all accesses
// to the data, we include this guard which should only involve
// compile-time constants. Ideally this should result in the branch
// only be included for types with excessive alignment.
let empty_header_is_aligned = if cfg!(feature = "gecko-ffi") {
// in gecko-ffi mode `padding` will ensure this under
// the assumption that the header has size 8 and the
// static empty singleton is aligned to 8.
true
} else {
// In non-gecko-ffi mode, the empty singleton is just
// naturally aligned to the Header. If the Header is at
// least as aligned as T *and* the padding would have
// been 0, then one-past-the-end of the empty singleton
// *is* a valid data pointer and we can remove the
// `dangling` special case.
mem::align_of::<Header>() >= mem::align_of::<T>() && padding == 0
};
unsafe {
if !empty_header_is_aligned && self.header().cap() == 0 {
NonNull::dangling().as_ptr()
} else {
// This could technically result in overflow, but padding
// would have to be absurdly large for this to occur.
let header_size = mem::size_of::<Header>();
let ptr = self.ptr.as_ptr() as *mut u8;
ptr.add(header_size + padding) as *mut T
}
}
}
// This is unsafe when the header is EMPTY_HEADER.
unsafe fn header_mut(&mut self) -> &mut Header {
&mut *self.ptr()
}
/// Returns the number of elements in the vector, also referred to
/// as its 'length'.
///
/// # Examples
///
/// ```
/// use thin_vec::thin_vec;
///
/// let a = thin_vec![1, 2, 3];
/// assert_eq!(a.len(), 3);
/// ```
pub fn len(&self) -> usize {
self.header().len()
}
/// Returns `true` if the vector contains no elements.
///
/// # Examples
///
/// ```
/// use thin_vec::ThinVec;
///
/// let mut v = ThinVec::new();
/// assert!(v.is_empty());
///
/// v.push(1);
/// assert!(!v.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the number of elements the vector can hold without
/// reallocating.
///
/// # Examples
///
/// ```
/// use thin_vec::ThinVec;
///
/// let vec: ThinVec<i32> = ThinVec::with_capacity(10);
/// assert_eq!(vec.capacity(), 10);
/// ```
pub fn capacity(&self) -> usize {
self.header().cap()
}
/// Returns `true` if the vector has the capacity to hold any element.
pub fn has_capacity(&self) -> bool {
!self.is_singleton()
}
/// 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`]: ThinVec::truncate
/// [`resize`]: ThinVec::resize
/// [`extend`]: ThinVec::extend
/// [`clear`]: ThinVec::clear
///
/// # Safety
///
/// - `new_len` must be less than or equal to [`capacity()`].
/// - The elements at `old_len..new_len` must be initialized.
///
/// [`capacity()`]: ThinVec::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
/// use thin_vec::ThinVec;
///
/// # // 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 std::ffi::c_void }
/// # const Z_OK: i32 = 0;
/// # extern "C" {
/// # fn deflateGetDictionary(
/// # strm: *mut std::ffi::c_void,
/// # dictionary: *mut u8,
/// # dictLength: *mut usize,
/// # ) -> i32;
/// # }
/// # impl StreamWrapper {
/// pub fn get_dictionary(&self) -> Option<ThinVec<u8>> {
/// // Per the FFI method's docs, "32768 bytes is always enough".
/// let mut dict = ThinVec::with_capacity(32_768);
/// 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:
///
/// ```no_run
/// use thin_vec::thin_vec;
///
/// let mut vec = thin_vec![thin_vec![1, 0, 0],
/// thin_vec![0, 1, 0],
/// thin_vec![0, 0, 1]];
/// // 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, len: usize) {
if self.is_singleton() {
// A prerequisite of `Vec::set_len` is that `new_len` must be
// less than or equal to capacity(). The same applies here.
assert!(len == 0, "invalid set_len({}) on empty ThinVec", len);
} else {
self.header_mut().set_len(len)
}
}
// For internal use only, when setting the length and it's known to be the non-singleton.
unsafe fn set_len_non_singleton(&mut self, len: usize) {
self.header_mut().set_len(len)
}
/// Appends an element to the back of a collection.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` bytes.
///
/// # Examples
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut vec = thin_vec![1, 2];
/// vec.push(3);
/// assert_eq!(vec, [1, 2, 3]);
/// ```
pub fn push(&mut self, val: T) {
let old_len = self.len();
if old_len == self.capacity() {
self.reserve(1);
}
unsafe {
ptr::write(self.data_raw().add(old_len), val);
self.set_len_non_singleton(old_len + 1);
}
}
/// Removes the last element from a vector and returns it, or [`None`] if it
/// is empty.
///
/// # Examples
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut vec = thin_vec![1, 2, 3];
/// assert_eq!(vec.pop(), Some(3));
/// assert_eq!(vec, [1, 2]);
/// ```
pub fn pop(&mut self) -> Option<T> {
let old_len = self.len();
if old_len == 0 {
return None;
}
unsafe {
self.set_len_non_singleton(old_len - 1);
Some(ptr::read(self.data_raw().add(old_len - 1)))
}
}
/// Inserts an element at position `index` within the vector, shifting all
/// elements after it to the right.
///
/// # Panics
///
/// Panics if `index > len`.
///
/// # Examples
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut vec = thin_vec![1, 2, 3];
/// vec.insert(1, 4);
/// assert_eq!(vec, [1, 4, 2, 3]);
/// vec.insert(4, 5);
/// assert_eq!(vec, [1, 4, 2, 3, 5]);
/// ```
pub fn insert(&mut self, idx: usize, elem: T) {
let old_len = self.len();
assert!(idx <= old_len, "Index out of bounds");
if old_len == self.capacity() {
self.reserve(1);
}
unsafe {
let ptr = self.data_raw();
ptr::copy(ptr.add(idx), ptr.add(idx + 1), old_len - idx);
ptr::write(ptr.add(idx), elem);
self.set_len_non_singleton(old_len + 1);
}
}
/// Removes and returns the element at position `index` within the vector,
/// shifting all elements after it to the left.
///
/// Note: Because this shifts over the remaining elements, it has a
/// worst-case performance of *O*(*n*). If you don't need the order of elements
/// to be preserved, use [`swap_remove`] instead. If you'd like to remove
/// elements from the beginning of the `ThinVec`, consider using `std::collections::VecDeque`.
///
/// [`swap_remove`]: ThinVec::swap_remove
///
/// # Panics
///
/// Panics if `index` is out of bounds.
///
/// # Examples
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut v = thin_vec![1, 2, 3];
/// assert_eq!(v.remove(1), 2);
/// assert_eq!(v, [1, 3]);
/// ```
pub fn remove(&mut self, idx: usize) -> T {
let old_len = self.len();
assert!(idx < old_len, "Index out of bounds");
unsafe {
self.set_len_non_singleton(old_len - 1);
let ptr = self.data_raw();
let val = ptr::read(self.data_raw().add(idx));
ptr::copy(ptr.add(idx + 1), ptr.add(idx), old_len - idx - 1);
val
}
}
/// 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).
/// If you need to preserve the element order, use [`remove`] instead.
///
/// [`remove`]: ThinVec::remove
///
/// # Panics
///
/// Panics if `index` is out of bounds.
///
/// # Examples
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut v = thin_vec!["foo", "bar", "baz", "qux"];
///
/// 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, idx: usize) -> T {
let old_len = self.len();
assert!(idx < old_len, "Index out of bounds");
unsafe {
let ptr = self.data_raw();
ptr::swap(ptr.add(idx), ptr.add(old_len - 1));
self.set_len_non_singleton(old_len - 1);
ptr::read(ptr.add(old_len - 1))
}
}
/// Shortens the vector, keeping the first `len` elements and dropping
/// the rest.
///
/// If `len` is greater than the vector's current length, this has no
/// effect.
///
/// The [`drain`] method can emulate `truncate`, but causes the excess
/// elements to be returned instead of dropped.
///
/// Note that this method has no effect on the allocated capacity
/// of the vector.
///
/// # Examples
///
/// Truncating a five element vector to two elements:
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut vec = thin_vec![1, 2, 3, 4, 5];
/// vec.truncate(2);
/// assert_eq!(vec, [1, 2]);
/// ```
///
/// No truncation occurs when `len` is greater than the vector's current
/// length:
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut vec = thin_vec![1, 2, 3];
/// vec.truncate(8);
/// assert_eq!(vec, [1, 2, 3]);
/// ```
///
/// Truncating when `len == 0` is equivalent to calling the [`clear`]
/// method.
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut vec = thin_vec![1, 2, 3];
/// vec.truncate(0);
/// assert_eq!(vec, []);
/// ```
///
/// [`clear`]: ThinVec::clear
/// [`drain`]: ThinVec::drain
pub fn truncate(&mut self, len: usize) {
unsafe {
// drop any extra elements
while len < self.len() {
// decrement len before the drop_in_place(), so a panic on Drop
// doesn't re-drop the just-failed value.
let new_len = self.len() - 1;
self.set_len_non_singleton(new_len);
ptr::drop_in_place(self.data_raw().add(new_len));
}
}
}
/// Clears the vector, removing all values.
///
/// Note that this method has no effect on the allocated capacity
/// of the vector.
///
/// # Examples
///
/// ```
/// use thin_vec::thin_vec;
///
/// let mut v = thin_vec![1, 2, 3];
/// v.clear();
/// assert!(v.is_empty());