unsized_vec/lib.rs
1//! [`UnsizedVec<T>`], like [`Vec<T>`][alloc::vec::Vec], is a contiguous growable array
2//! type with heap-allocated contents. Unlike [`Vec<T>`], it can store unsized values.
3//!
4//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
5//! *O*(1) pop (from the end). When `T` is [`Sized`], they use one heap
6//! allocation; when it is not, they use two.
7//!
8//! This crate is nightly-only and experimental.
9//!
10//! # Examples
11//!
12//! You can explicitly create an [`UnsizedVec`] with [`UnsizedVec::new`]:
13//!
14//! ```
15//! # use unsized_vec::UnsizedVec;
16//! let v: UnsizedVec<i32> = UnsizedVec::new();
17//! ```
18//!
19//! ...or by using the [`unsize_vec!`] macro:
20//!
21//! ```
22//! # use core::fmt::Debug;
23//! # use unsized_vec::{unsize_vec, UnsizedVec};
24//! let v: UnsizedVec<[u32]> = unsize_vec![];
25//!
26//! let v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!", 3.0_f64, (), -17_i32];
27//! ```
28//!
29//! You can [`push`] or [`push_unsize`] values onto the end of a vector (which will grow the vector
30//! as needed):
31//!
32//! ```
33//! # use core::fmt::Debug;
34//! # use unsized_vec::{unsize_vec, UnsizedVec};
35//! let mut v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!", 3.0_f64, (), -17_i32];
36//!
37//! v.push_unsize(3);
38//! ```
39//!
40//! Popping values works in much the same way:
41//!
42//! ```
43//! # use core::fmt::Debug;
44//! # use emplacable::box_new_with;
45//! # use unsized_vec::{unsize_vec, UnsizedVec};
46//! let mut v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!"];
47//!
48//! // "hello!" is copied directly into a new heap allocation
49//! let two: Option<Box<dyn Debug>> = v.pop_into().map(box_new_with);
50//! ```
51//!
52//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
53//!
54//! ```
55//! # use core::fmt::Debug;
56//! # use unsized_vec::{unsize_vec, UnsizedVec};
57//! let mut v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!", [(); 0]];
58//! let greeting = &v[1];
59//! dbg!(greeting);
60//! ```
61//! [`Vec<T>`]: alloc::vec::Vec
62//! [`push`]: UnsizedVec::push
63//! [`push_unsize`]: UnsizedVec::push_unsize
64
65#![allow(
66 incomplete_features, // For `specialization`
67 internal_features, // for `unsized_fn_params`
68)]
69#![feature(
70 allocator_api,
71 array_windows,
72 forget_unsized,
73 int_roundings,
74 ptr_metadata,
75 // We avoid specializing based on subtyping,
76 // so barring compiler bugs, our usage should be sound.
77 specialization,
78 try_reserve_kind,
79 type_alias_impl_trait,
80 unsize,
81 unsized_fn_params,
82)]
83#![no_std]
84
85mod helper;
86mod inner;
87mod marker;
88
89#[doc(hidden)]
90pub extern crate alloc;
91use alloc::{alloc::handle_alloc_error, collections::TryReserveErrorKind};
92use core::{
93 self, cmp,
94 fmt::{self, Debug, Formatter},
95 hash::Hash,
96 iter::FusedIterator,
97 marker::Unsize,
98 mem,
99 ops::{Index, IndexMut},
100};
101use emplacable::{Emplacable, EmplacableFn, Emplacer, unsize};
102
103use inner::{Align, Size, UnsizedVecImpl, UnsizedVecProvider};
104
105/// The error type for `try_reserve` methods.
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub struct TryReserveError {
108 kind: TryReserveErrorKind,
109}
110
111#[track_caller]
112#[inline]
113fn to_align<T: ?Sized>(align: usize) -> AlignTypeFor<T> {
114 #[cold]
115 #[inline(never)]
116 fn invalid_align(align: usize) -> ! {
117 panic!("align {align} is not a power of 2")
118 }
119
120 let Some(ret) = AlignTypeFor::<T>::new(align) else {
121 invalid_align(align)
122 };
123
124 ret
125}
126
127#[track_caller]
128#[inline]
129fn unwrap_try_reserve_result<T>(result: Result<T, TryReserveError>) -> T {
130 #[cold]
131 #[inline(never)]
132 fn handle_err(e: TryReserveError) -> ! {
133 match e.kind {
134 TryReserveErrorKind::CapacityOverflow => panic!("Capacity overflowed `isize::MAX`"),
135 TryReserveErrorKind::AllocError { layout, .. } => handle_alloc_error(layout),
136 }
137 }
138
139 match result {
140 Ok(val) => val,
141 Err(e) => handle_err(e),
142 }
143}
144
145impl From<::alloc::collections::TryReserveError> for TryReserveError {
146 fn from(value: ::alloc::collections::TryReserveError) -> Self {
147 TryReserveError { kind: value.kind() }
148 }
149}
150
151type AlignTypeFor<T> = <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::Align;
152type SizeTypeFor<T> = <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::Size;
153
154/// Like [`Vec`][0], but can store unsized values.
155///
156/// # Memory layout
157///
158/// `UnsizedVec` is actually three different types rolled in to one;
159/// specialization is used to choose the optimal implementation based on the properties
160/// of `T`.
161///
162/// 1. When `T` is a [`Sized`] type, `UnsizedVec<T>` is a newtype around [`Vec<T>`][0],
163/// with exactly the same memoy layout.
164///
165/// 2. When `T` is a slice, there are two heap allocations.
166/// The first is to the slices themsleves; they are laid out end-to-end, one after the other,
167/// with no padding in between. The second heap allocation is to a list of offsets, to store
168/// where each element begins and ends.
169///
170/// 3. When `T` is neither of the above, there are still two allocations.
171/// The first allocation still contains the elements of the vector laid out end-to-end,
172/// but now every element is padded to at least the alignment of the most-aligned element
173/// in the `UnsizedVec`. For this reason, adding a new element to the vec with a larger alignment
174/// than any of the elements already in it will add new padding to all the existing elements,
175/// which will involve a lot of copying and probably a reallocation. By default, [`UnsizedVec::new`]
176/// sets the alignment to [`core::mem::align_of::<usize>()`], so as long as none of your trait objects
177/// are aligned to more than that, you won't have to worry about re-padding.
178/// For this last case, the second allocation, in addition to storing offsets, also stores the pointer
179/// metadata of each element.
180///
181/// ## Managing capacity
182///
183/// [`Vec<T>`][0] has only one kind of capacity to worry about: elementwise capacity. And so does
184/// `UnsizedVec<T>`, as long as `T: Sized`. You can use functions like [`capacity`], [`with_capacity`]
185/// and [`reserve`] to manage this capacity.
186///
187/// When `T` is a slice, there are two kinds of capacities: element capacity and byte capacity.
188/// Adding new elements to the vec is guaranteed not to reallocate as long as
189/// the number of elements doesn't exceed the element capacity *and* the total size of all
190/// the elements in bytes doesn't exceed the byte capacity. You can use functions like
191/// [`byte_capacity`], [`with_capacity_bytes`], and [`reserve_capacity_bytes`] to manage
192/// these two capacities.
193///
194/// When `T` is a trait object, there is a third type of capacity: alignment. To avoid
195/// reallocation when adding a new element to the vec, you need to ensure that you have
196/// sufficient element and byte capacity, and that the vec's align is not less than the
197/// alignment of the new element. Functions like [`align`], [`with_capacity_bytes_align`], and
198/// [`reserve_capacity_bytes_align`], can be used to manage all three capacities in this case.
199///
200/// # Limitations
201///
202/// - `UnsizedVec<T>` is invariant with respect to `T`; ideally, it should be covariant.
203/// This is because Rust forces invariance on all structs that contain associated types
204/// referencing `T`. Hopefully, future language features will allow lifting this limitation.
205/// - Rust functions can't directly return unsized types. So this crate's functions return
206/// them indirectly, though the "emplacer" mechanism defined in the [`emplacable`] crate.
207/// See that crate's documentation for details, and the documentation of [`pop_into`] and
208/// [`remove_into`] for usage examples.
209///
210/// # Example
211///
212/// ```
213/// #![allow(internal_features)] // for `unsized_fn_params`
214/// #![feature(unsized_fn_params)]
215/// use core::fmt::Debug;
216///
217/// use emplacable::box_new_with;
218/// use unsized_vec::{unsize_vec, UnsizedVec};
219///
220/// let mut vec: UnsizedVec<dyn Debug> = unsize_vec![27.53_f32, "oh the places we'll go", Some(())];
221///
222/// for traitobj in &vec {
223/// dbg!(traitobj);
224/// };
225///
226/// assert_eq!(vec.len(), 3);
227///
228/// let maybe_popped: Option<Box<dyn Debug>> = vec.pop_into().map(box_new_with);
229/// let popped = maybe_popped.unwrap();
230/// dbg!(&*popped);
231///
232/// assert_eq!(vec.len(), 2);
233/// ```
234///
235/// [0]: alloc::vec::Vec
236/// [`emplacable`]: emplacable
237/// [`capacity`]: UnsizedVec::capacity
238/// [`with_capacity`]: UnsizedVec::with_capacity
239/// [`reserve`]: UnsizedVec::reserve
240/// [`byte_capacity`]: UnsizedVec::byte_capacity
241/// [`with_capacity_bytes`]: UnsizedVec::with_capacity_bytes
242/// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
243/// [`align`]: UnsizedVec::align
244/// [`with_capacity_bytes_align`]: UnsizedVec::with_capacity_bytes_align
245/// [`reserve_capacity_bytes_align`]: UnsizedVec::reserve_capacity_bytes_align
246/// [`pop_into`]: UnsizedVec::pop_into
247/// [`remove_into`]: UnsizedVec::remove_into
248#[repr(transparent)]
249pub struct UnsizedVec<T>
250where
251 T: ?Sized,
252{
253 inner: <T as UnsizedVecImpl>::Impl,
254}
255
256impl<T: ?Sized> UnsizedVec<T> {
257 /// Create a new, empty `UnsizedVec`.
258 /// Does not allocate.
259 ///
260 /// When `T`'s alignmnent is not known
261 /// at compile-time, this uses `mem::align_of::<usize>()`
262 /// as the default alignment.
263 #[must_use]
264 #[inline]
265 pub const fn new() -> UnsizedVec<T> {
266 UnsizedVec {
267 inner: UnsizedVecProvider::NEW_ALIGN_PTR,
268 }
269 }
270
271 /// Create a new, empty `UnsizedVec` with the given capacity.
272 ///
273 /// When `T`'s alignmnent is not known
274 /// at compile-time, this uses `mem::align_of::<usize>()`
275 /// as the default alignment.
276 #[must_use]
277 #[inline]
278 pub fn with_capacity(capacity: usize) -> UnsizedVec<T> {
279 let mut vec = UnsizedVec::new();
280 vec.reserve_exact(capacity);
281 vec
282 }
283
284 /// Create a new, empty `UnsizedVec` with the given capacity.
285 /// (When `T: Aligned` does not hold, an alignment of 1 is used.)
286 ///
287 /// When `T`'s alignmnent is not known
288 /// at compile-time, this uses `mem::align_of::<usize>()`
289 /// as the default alignment.
290 #[must_use]
291 #[inline]
292 pub fn with_capacity_bytes(capacity: usize, byte_capacity: usize) -> UnsizedVec<T> {
293 let mut vec = UnsizedVec::new();
294 vec.reserve_exact_capacity_bytes(capacity, byte_capacity);
295 vec
296 }
297
298 /// Create a new, empty `UnsizedVec` with the given capacity
299 /// (in bytes) and alignment.
300 ///
301 /// `align` is ignored when `T`'s alignment is known at compile time
302 #[must_use]
303 #[inline]
304 pub fn with_capacity_bytes_align(
305 capacity: usize,
306 byte_capacity: usize,
307 align: usize,
308 ) -> UnsizedVec<T> {
309 let mut vec = UnsizedVec {
310 inner: UnsizedVecProvider::NEW_ALIGN_1,
311 };
312 vec.reserve_exact_capacity_bytes_align(capacity, byte_capacity, align);
313 vec
314 }
315
316 /// Returns the number of elements the vector can hold without
317 /// reallocating.
318 ///
319 /// For `T: ?Sized`, this only concers whether metadata
320 /// could get reallocated, not the elements themselves.
321 #[must_use]
322 #[inline]
323 pub fn capacity(&self) -> usize {
324 self.inner.capacity()
325 }
326
327 /// Returns the number of bytes the vector can hold without
328 /// reallocating.
329 #[must_use]
330 #[inline]
331 pub fn byte_capacity(&self) -> usize {
332 self.inner.byte_capacity()
333 }
334
335 /// Returns the maximum alignment of the values this vector
336 /// can hold without re-padding and reallocating.
337 ///
338 /// Only relevant when `T`'s alignment is not known at compile time.
339 #[must_use]
340 #[inline]
341 pub fn align(&self) -> usize {
342 self.inner.align()
343 }
344
345 /// Reserves capacity for at least `additional` more elements to be inserted
346 /// in the given `UnsizedVec<T>`. The collection may reserve more space to
347 /// speculatively avoid frequent reallocations.
348 ///
349 /// When `T` is not `Sized`, this only reseves space to store *metadata*.
350 /// Consider using [`reserve_capacity_bytes`] instead in such cases.
351 ///
352 /// # Panics
353 ///
354 /// Panics if the new capacity exceeds `isize::MAX` bytes.
355 ///
356 /// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
357 #[inline]
358 pub fn reserve(&mut self, additional: usize) {
359 unwrap_try_reserve_result(self.try_reserve(additional));
360 }
361
362 /// Reserves capacity for at least `additional` more elements,
363 /// taking up at least `additional_bytes` bytes of space, to be inserted
364 /// in the given `UnsizedVec<T>`. The collection may reserve more space to
365 /// speculatively avoid frequent reallocations.
366 ///
367 /// When `T`'s alignment is not known at compile time,
368 /// the vec may still reallocate if you push a new element onto the
369 /// vec with an alignment greater than `self.align()`. Consider
370 /// using [`reserve_capacity_bytes_align`] instead in such cases.
371 ///
372 /// # Panics
373 ///
374 /// Panics if the either of the new capacities exceeds `isize::MAX` bytes.
375 ///
376 /// [`reserve_capacity_bytes_align`]: UnsizedVec::reserve_capacity_bytes_align
377 #[inline]
378 pub fn reserve_capacity_bytes(&mut self, additional: usize, additional_bytes: usize) {
379 unwrap_try_reserve_result(self.try_reserve_capacity_bytes(additional, additional_bytes));
380 }
381
382 /// Reserves capacity for at least `additional` more elements,
383 /// taking up at least `additional_bytes` bytes of space,
384 /// and with alignment of at most `align`, to be inserted
385 /// in the given `UnsizedVec<T>`. The collection may reserve more space to
386 /// speculatively avoid frequent reallocations.
387 ///
388 /// When `T`'s alignment is known at compile time,
389 /// `align` is ignored. Consider using [`reserve_capacity_bytes`]
390 /// instead in such cases.
391 ///
392 /// # Panics
393 ///
394 /// Panics if the either of the new capacities exceeds `isize::MAX` bytes,
395 /// or if `align` is not a power of two.
396 ///
397 /// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
398 #[inline]
399 pub fn reserve_capacity_bytes_align(
400 &mut self,
401 additional: usize,
402 additional_bytes: usize,
403 align: usize,
404 ) {
405 unwrap_try_reserve_result(self.try_reserve_capacity_bytes_align(
406 additional,
407 additional_bytes,
408 align,
409 ));
410 }
411
412 /// Reserves capacity for at least `additional` more elements to be inserted
413 /// in the given `UnsizedVec<T>`. Unlike [`reserve`], this will not
414 /// deliberately over-allocate to speculatively avoid frequent allocations.
415 ///
416 /// When `T` is not `Sized`, this only reseves space to store *metadata*.
417 /// Consider using [`reserve_exact_capacity_bytes`] instead in such cases.
418 ///
419 /// # Panics
420 ///
421 /// Panics if the new capacity exceeds `isize::MAX` bytes.
422 ///
423 /// [`reserve`]: UnsizedVec::reserve
424 /// [`reserve_exact_capacity_bytes`]: UnsizedVec::reserve_exact_capacity_bytes
425 #[inline]
426 pub fn reserve_exact(&mut self, additional: usize) {
427 unwrap_try_reserve_result(self.try_reserve_exact_capacity_bytes(additional, 0));
428 }
429
430 /// Reserves capacity for at least `additional` more elements,
431 /// taking up at least `additional_bytes` bytes of space, to be inserted
432 /// in the given `UnsizedVec<T>`. Unlike [`reserve_capacity_bytes`], this will not
433 /// deliberately over-allocate to speculatively avoid frequent allocations.
434 ///
435 /// When `T`'s alignment is not known at compile time,
436 /// the vec may still reallocate if you push a new element onto the
437 /// vec with an alignment greater than `self.align()`. Consider
438 /// using [`reserve_exact_capacity_bytes_align`] instead in such cases.
439 ///
440 /// # Panics
441 ///
442 /// Panics if the new capacity exceeds `isize::MAX` bytes.
443 ///
444 /// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
445 /// [`reserve_exact_capacity_bytes_align`]: UnsizedVec::reserve_exact_capacity_bytes_align
446 #[inline]
447 pub fn reserve_exact_capacity_bytes(&mut self, additional: usize, additional_bytes: usize) {
448 unwrap_try_reserve_result(
449 self.try_reserve_exact_capacity_bytes(additional, additional_bytes),
450 );
451 }
452
453 /// Reserves capacity for at least `additional` more elements,
454 /// taking up at least `additional_bytes` bytes of space,
455 /// and with alignment of at most `align`, to be inserted
456 /// in the given `UnsizedVec<T>`. Unlike [`reserve_capacity_bytes_align`], this will not
457 /// deliberately over-allocate to speculatively avoid frequent allocations.
458 ///
459 /// When `T`'s alignment is known at compile time,
460 /// `align` is ignored. Consider using [`reserve_exact_capacity_bytes`]
461 /// instead in such cases.
462 ///
463 /// # Panics
464 ///
465 /// Panics if the new capacity exceeds `isize::MAX` bytes.
466 ///
467 /// [`reserve_capacity_bytes_align`]: UnsizedVec::reserve_capacity_bytes_align
468 /// [`reserve_exact_capacity_bytes`]: UnsizedVec::reserve_exact_capacity_bytes
469 #[inline]
470 pub fn reserve_exact_capacity_bytes_align(
471 &mut self,
472 additional: usize,
473 additional_bytes: usize,
474 align: usize,
475 ) {
476 unwrap_try_reserve_result(self.try_reserve_exact_capacity_bytes_align(
477 additional,
478 additional_bytes,
479 align,
480 ));
481 }
482
483 /// Reserves capacity for at least `additional` more elements to be inserted
484 /// in the given `UnsizedVec<T>`. The collection may reserve more space to
485 /// speculatively avoid frequent reallocations.
486 ///
487 /// When `T` is not `Sized`, this only reseves space to store *metadata*.
488 /// Consider using [`try_reserve_capacity_bytes`] instead in such cases.
489 ///
490 /// # Errors
491 ///
492 /// If the capacity overflows, or the allocator reports a failure, then an error
493 /// is returned.
494 ///
495 /// [`try_reserve_capacity_bytes`]: UnsizedVec::try_reserve_capacity_bytes
496 #[inline]
497 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
498 self.inner.try_reserve(additional)
499 }
500
501 /// Reserves capacity for at least `additional` more elements,
502 /// taking up at least `additional_bytes` bytes of space, to be inserted
503 /// in the given `UnsizedVec<T>`. The collection may reserve more space to
504 /// speculatively avoid frequent reallocations.
505 ///
506 /// When `T`'s alignment is not known at compile time,
507 /// the vec may still reallocate if you push a new element onto the
508 /// vec with an alignment greater than `self.align()`. Consider
509 /// using [`try_reserve_capacity_bytes_align`] instead in such cases.
510 ///
511 /// # Errors
512 ///
513 /// If the capacity overflows, or the allocator reports a failure, then an error
514 /// is returned.
515 ///
516 /// [`try_reserve_capacity_bytes_align`]: UnsizedVec::try_reserve_capacity_bytes_align
517 #[inline]
518 pub fn try_reserve_capacity_bytes(
519 &mut self,
520 additional: usize,
521 additional_bytes: usize,
522 ) -> Result<(), TryReserveError> {
523 self.try_reserve_capacity_bytes_align(additional, additional_bytes, 1)
524 }
525
526 /// Reserves capacity for at least `additional` more elements,
527 /// taking up at least `additional_bytes` bytes of space,
528 /// and with alignment of at most `align`, to be inserted
529 /// in the given `UnsizedVec<T>`. The collection may reserve more space to
530 /// speculatively avoid frequent reallocations.
531 ///
532 /// When `T`'s alignment is known at compile time,
533 /// `align` is ignored. Consider using [`try_reserve_capacity_bytes`]
534 /// instead in such cases.
535 ///
536 /// # Errors
537 ///
538 /// If the capacity overflows, or the allocator reports a failure, then an error
539 /// is returned.
540 ///
541 /// # Panics
542 ///
543 /// Panics if `align` is not a power of two.
544 ///
545 /// [`try_reserve_capacity_bytes`]: UnsizedVec::try_reserve_capacity_bytes
546 #[inline]
547 pub fn try_reserve_capacity_bytes_align(
548 &mut self,
549 additional: usize,
550 additional_bytes: usize,
551 align: usize,
552 ) -> Result<(), TryReserveError> {
553 self.try_reserve(additional)?;
554
555 debug_assert!(self.capacity() >= self.len() + additional);
556
557 let align = to_align::<T>(align);
558
559 let byte_cap = self.byte_capacity();
560
561 let needed_bytes = additional_bytes.saturating_sub(self.unused_byte_cap());
562
563 let optimist_bytes = if needed_bytes > 0 {
564 cmp::max(needed_bytes, byte_cap)
565 } else {
566 0
567 };
568
569 // First we try to double capacities.
570 // if that fails, we try again with only what we really need.
571 if optimist_bytes > needed_bytes {
572 let result = self
573 .inner
574 .try_reserve_additional_bytes_align(optimist_bytes, align);
575
576 if result.is_ok() {
577 return result;
578 }
579 }
580
581 let result = self
582 .inner
583 .try_reserve_additional_bytes_align(needed_bytes, align);
584
585 debug_assert!(self.byte_capacity() >= self.byte_len() + additional_bytes);
586
587 result
588 }
589
590 /// Reserves capacity for at least `additional` more elements to be inserted
591 /// in the given `UnsizedVec<T>`. Unlike [`try_reserve`], this will not
592 /// deliberately over-allocate to speculatively avoid frequent allocations.
593 ///
594 /// When `T` is not `Sized`, this only reseves space to store *metadata*.
595 /// Consider using [`try_reserve_exact_capacity_bytes`] instead in such cases.
596 ///
597 /// # Errors
598 ///
599 /// If the capacity overflows, or the allocator reports a failure, then an error
600 /// is returned.
601 ///
602 /// [`try_reserve`]: UnsizedVec::try_reserve
603 /// [`try_reserve_exact_capacity_bytes`]: UnsizedVec::try_reserve_exact_capacity_bytes
604 #[inline]
605 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
606 self.inner.try_reserve_exact(additional)
607 }
608
609 /// Reserves capacity for at least `additional` more elements,
610 /// taking up at least `additional_bytes` bytes of space, to be inserted
611 /// in the given `UnsizedVec<T>`. Unlike [`try_reserve_capacity_bytes`], this will not
612 /// deliberately over-allocate to speculatively avoid frequent allocations.
613 ///
614 /// When `T`'s alignment is not known at compile time,
615 /// the vec may still reallocate if you push a new element onto the
616 /// vec with an alignment greater than `self.align()`. Consider
617 /// using [`try_reserve_exact_capacity_bytes_align`] instead in such cases.
618 ///
619 /// # Errors
620 ///
621 /// If the capacity overflows, or the allocator reports a failure, then an error
622 /// is returned.
623 ///
624 /// [`try_reserve_capacity_bytes`]: UnsizedVec::try_reserve_capacity_bytes
625 /// [`try_reserve_exact_capacity_bytes_align`]: UnsizedVec::try_reserve_exact_capacity_bytes_align
626 #[inline]
627 pub fn try_reserve_exact_capacity_bytes(
628 &mut self,
629 additional: usize,
630 additional_bytes: usize,
631 ) -> Result<(), TryReserveError> {
632 self.try_reserve_exact_capacity_bytes_align(additional, additional_bytes, 1)
633 }
634
635 /// Reserves capacity for at least `additional` more elements,
636 /// taking up at least `additional_bytes` bytes of space,
637 /// and with alignment of at most `align`, to be inserted
638 /// in the given `UnsizedVec<T>`. Unlike [`try_reserve_capacity_bytes_align`], this will not
639 /// deliberately over-allocate to speculatively avoid frequent allocations.
640 ///
641 /// When `T`'s alignment is known at compile time,
642 /// `align` is ignored. Consider using [`try_reserve_exact_capacity_bytes`]
643 /// instead in such cases.
644 ///
645 /// # Errors
646 ///
647 /// If the capacity overflows, or the allocator reports a failure, then an error
648 /// is returned.
649 ///
650 /// # Panics
651 ///
652 /// Panics if `align` is not a power of two.
653 ///
654 /// [`try_reserve_capacity_bytes_align`]: UnsizedVec::try_reserve_capacity_bytes_align
655 /// [`try_reserve_exact_capacity_bytes`]: UnsizedVec::try_reserve_exact_capacity_bytes
656 #[inline]
657 pub fn try_reserve_exact_capacity_bytes_align(
658 &mut self,
659 additional: usize,
660 additional_bytes: usize,
661 align: usize,
662 ) -> Result<(), TryReserveError> {
663 self.inner.try_reserve(additional)?;
664 let align = to_align::<T>(align);
665
666 self.inner
667 .try_reserve_additional_bytes_align(additional_bytes, align)
668 }
669
670 /// Shrinks all the capacities of the vec as much as possible.
671 #[inline]
672 pub fn shrink_to_fit(&mut self) {
673 self.inner
674 .shrink_capacity_bytes_align_to(0, 0, to_align::<T>(1));
675 }
676
677 /// Shrinks the elementwise capacity of the vector with a lower bound.
678 ///
679 /// The capacity will remain at least as large as both the length
680 /// and the supplied value.
681 ///
682 /// If the current capacity is less than the lower limit, this is a no-op.
683 ///
684 /// For `T: ?Sized`, this only effects elementwise capacity.
685 /// Consider using [`shrink_capacity_bytes_to`] in such cases.
686 ///
687 /// [`shrink_capacity_bytes_to`]: UnsizedVec::shrink_capacity_bytes_to
688 #[inline]
689 pub fn shrink_to(&mut self, min_capacity: usize) {
690 self.inner.shrink_capacity_bytes_align_to(
691 min_capacity,
692 usize::MAX,
693 to_align::<T>(1 << (usize::BITS - 1)),
694 );
695 }
696
697 /// Shrinks the elementwise and byte capacities of the vector with
698 /// lower bounds.
699 ///
700 /// The capacities will remain at least as large as both the lengths
701 /// and the supplied values.
702 ///
703 /// If the current capacities are less than the lower limits, this is a no-op.
704 ///
705 /// When `T`'s alignment is not known at compile-time, this only effects elementwise
706 /// and bytewise capacities.
707 /// Consider using [`shrink_capacity_bytes_align_to`] in such cases.
708 ///
709 /// [`shrink_capacity_bytes_align_to`]: UnsizedVec::shrink_capacity_bytes_align_to
710 #[inline]
711 pub fn shrink_capacity_bytes_to(&mut self, min_capacity: usize, min_byte_capacity: usize) {
712 self.inner.shrink_capacity_bytes_align_to(
713 min_capacity,
714 min_byte_capacity,
715 to_align::<T>(1 << (usize::BITS - 1)),
716 );
717 }
718
719 /// Shrinks the elementwise, byte, and alignment capacities of the vector with
720 /// lower bounds.
721 ///
722 /// The capacities will remain at least as large as both the lengths
723 /// and the supplied values.
724 ///
725 /// If the current capacities are less than the lower limits, this is a no-op.
726 ///
727 /// # Panics
728 ///
729 /// Panics if `min_align` is not a power of two.
730 #[inline]
731 pub fn shrink_capacity_bytes_align_to(
732 &mut self,
733 min_capacity: usize,
734 min_byte_capacity: usize,
735 min_align: usize,
736 ) {
737 self.inner.shrink_capacity_bytes_align_to(
738 min_capacity,
739 min_byte_capacity,
740 to_align::<T>(min_align),
741 );
742 }
743
744 /// Inserts an element at position `index` within the vector, shifting all
745 /// elements after it to the right.
746 ///
747 /// If `T` is not `Sized`, you will need
748 /// `#![feature(unsized_fn_params)]` to call this.
749 /// You may also need the [`unsize`] macro, which
750 /// requires additional nightly features.
751 ///
752 /// Alternatively, you can use [`insert_unsize`][0],
753 /// which takes care of unsizing for you.
754 ///
755 /// # Example
756 ///
757 /// ```
758 /// #![allow(internal_features)] // for `unsized_fn_params`
759 /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
760 ///
761 /// use core::fmt::Debug;
762 ///
763 /// use emplacable::unsize;
764 /// use unsized_vec::UnsizedVec;
765 ///
766 /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
767 ///
768 /// vec.push(unsize!([1, 2], ([i32; 2]) -> dyn Debug));
769 /// vec.insert(0, unsize!("can you believe it", (&str) -> dyn Debug));
770 /// dbg!(&vec[0]);
771 /// ```
772 ///
773 /// [0]: UnsizedVec::insert_unsize
774 #[inline]
775 pub fn insert(&mut self, index: usize, value: T) {
776 #[track_caller]
777 #[cold]
778 #[inline(never)]
779 fn assert_failed(index: usize, len: usize) -> ! {
780 panic!("insertion index (is {index}) should be <= len (is {len})");
781 }
782
783 if index <= self.len() {
784 let size_of_val = SizeTypeFor::<T>::of_val(&value);
785 self.reserve_capacity_bytes_align(1, size_of_val.get(), mem::align_of_val(&value));
786
787 // SAFETY: reserved needed capacity and performed bounds check above
788 unsafe { self.inner.insert_unchecked(index, value, size_of_val) }
789 } else {
790 assert_failed(index, self.len())
791 }
792 }
793
794 /// Appends an element to the back of a collection
795 /// after unsizing it.
796 ///
797 /// # Examples
798 ///
799 /// ```
800 /// use core::fmt::Debug;
801 ///
802 /// use unsized_vec::UnsizedVec;
803 ///
804 /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
805 ///
806 /// vec.push_unsize([1, 2]);
807 /// vec.insert_unsize(0, "can you believe it");
808 /// dbg!(&vec[0]);
809 /// ```
810 #[inline]
811 pub fn insert_unsize<S>(&mut self, index: usize, value: S)
812 where
813 S: Unsize<T>,
814 {
815 self.insert(index, unsize!(value, (S) -> T));
816 }
817
818 /// Inserts an element at position `index` within the vector, shifting all
819 /// elements after it to the right.
820 ///
821 /// Accepts the element as an [`Emplacable<T, _>`]
822 /// instead of `T` directly, analogously
823 /// to [`emplacable::box_new_with`].
824 ///
825 /// # Example
826 ///
827 /// ```
828 /// #![allow(internal_features)] // for `unsized_fn_params`
829 /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
830 ///
831 /// use core::fmt::Debug;
832 ///
833 /// use unsized_vec::{unsize_vec, UnsizedVec};
834 ///
835 /// let mut vec_1: UnsizedVec<dyn Debug> = unsize_vec![32, "hello"];
836 /// let mut vec_2: UnsizedVec<dyn Debug> = unsize_vec![97];
837 ///
838 /// vec_2.insert_with(0, vec_1.pop_into().unwrap());
839 ///
840 /// assert_eq!(vec_1.len(), 1);
841 /// assert_eq!(vec_2.len(), 2);
842 /// dbg!(&vec_2[0]);
843 /// ```
844 #[inline]
845 pub fn insert_with(&mut self, index: usize, value: Emplacable<T, impl EmplacableFn<T>>) {
846 #[track_caller]
847 #[cold]
848 #[inline(never)]
849 fn assert_failed(index: usize, len: usize) -> ! {
850 panic!("insertion index (is {index}) should be <= len (is {len})");
851 }
852
853 if index <= self.len() {
854 // SAFETY: did bounds check just above
855 unsafe { self.inner.insert_with_unchecked(index, value) }
856 } else {
857 assert_failed(index, self.len())
858 }
859 }
860
861 /// Removes and returns the element at position `index` within the vector,
862 /// shifting all elements after it to the left.
863 ///
864 /// Because `T` might be unsized, and functions can't return
865 /// unsized values directly, this method returns the element using
866 /// the "emplacer" mechanism. You can pass the returned [`Emplacable<T, _>`]
867 /// to a function like [`box_new_with`] to get the contained `T`.
868 ///
869 /// # Example
870 ///
871 /// ```
872 /// use core::fmt::Debug;
873 ///
874 /// use emplacable::box_new_with;
875 /// use unsized_vec::UnsizedVec;
876 ///
877 /// let mut vec = UnsizedVec::<dyn Debug>::new();
878 ///
879 /// vec.push_unsize("A beautiful day today innit");
880 /// vec.push_unsize("Quite right ol chap");
881 ///
882 /// let popped: Box<dyn Debug> = box_new_with(vec.remove_into(0));
883 /// dbg!(&popped);
884 ///
885 /// ```
886 ///
887 /// [`box_new_with`]: emplacable::box_new_with
888 #[inline]
889 pub fn remove_into(&mut self, index: usize) -> Emplacable<T, impl EmplacableFn<T> + '_> {
890 #[track_caller]
891 #[cold]
892 #[inline(never)]
893 fn assert_failed(index: usize, len: usize) -> ! {
894 panic!("removal index (is {index}) should be < len (is {len})");
895 }
896
897 if index < self.len() {
898 let closure = move |emplacer: &mut Emplacer<'_, T>| {
899 // SAFETY: check `index < len` right above
900 unsafe { self.inner.remove_into_unchecked(index, emplacer) };
901 };
902 // SAFETY: `remove_into_unchecked` upholds the requirements
903 unsafe { Emplacable::from_fn(closure) }
904 } else {
905 assert_failed(index, self.len())
906 }
907 }
908
909 /// Appends an element to the back of a collection.
910 ///
911 /// If `T` is not `Sized`, you will need
912 /// `#![feature(unsized_fn_params)]` to call this.
913 /// You may also need the [`unsize`] macro, which
914 /// requires additional nightly features.
915 ///
916 /// Alternatively, you can use [`push_unsize`][0],
917 /// which takes care of unsizing for you.
918 ///
919 /// # Example
920 ///
921 /// ```
922 /// #![allow(internal_features)] // for `unsized_fn_params`
923 /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
924 ///
925 /// use core::fmt::Debug;
926 ///
927 /// use emplacable::unsize;
928 /// use unsized_vec::UnsizedVec;
929 ///
930 /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
931 ///
932 /// vec.push(unsize!([1, 2], ([i32; 2]) -> dyn Debug));
933 /// dbg!(&vec[0]);
934 /// ```
935 ///
936 /// [0]: UnsizedVec::push_unsize
937 #[inline]
938 pub fn push(&mut self, value: T) {
939 let size_of_val = SizeTypeFor::<T>::of_val(&value);
940
941 self.reserve_capacity_bytes_align(1, size_of_val.get(), mem::align_of_val(&value));
942
943 // SAFETY: reserved needed capacity above
944 unsafe { self.inner.push_unchecked(value, size_of_val) }
945 }
946
947 /// Appends an element to the back of a collection
948 /// after coercing it to an unsized type.
949 ///
950 /// # Example
951 ///
952 /// ```
953 /// use core::fmt::Debug;
954 ///
955 /// use unsized_vec::UnsizedVec;
956 ///
957 /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
958 ///
959 /// vec.push_unsize([1, 2]);
960 /// dbg!(&vec[0]);
961 ///
962 /// ```
963 #[inline]
964 pub fn push_unsize<S: Unsize<T>>(&mut self, value: S) {
965 self.push(unsize!(value, (S) -> T));
966 }
967
968 /// Appends an element to the back of a collection.
969 ///
970 /// Accepts the element as an [`Emplacable<T, _>`]
971 /// instead of `T` directly, analogously
972 /// to [`emplacable::box_new_with`].
973 ///
974 /// ```
975 /// #![allow(internal_features)] // for `unsized_fn_params`
976 /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
977 ///
978 /// use core::fmt::Debug;
979 ///
980 /// use unsized_vec::{unsize_vec, UnsizedVec};
981 ///
982 /// let mut vec_1: UnsizedVec<dyn Debug> = unsize_vec![32, "hello"];
983 /// let mut vec_2: UnsizedVec<dyn Debug> = UnsizedVec::new();
984 ///
985 /// vec_2.push_with(vec_1.pop_into().unwrap());
986 ///
987 /// assert_eq!(vec_1.len(), 1);
988 /// dbg!(&vec_2[0]);
989 /// ```
990 #[inline]
991 pub fn push_with(&mut self, value: Emplacable<T, impl EmplacableFn<T>>) {
992 self.inner.push_with(value);
993 }
994
995 /// Removes the last element from a vector and returns it, or [`None`] if it
996 /// is empty.
997 ///
998 /// Because `T` might be unsized, and functions can't return
999 /// unsized values directly, this method returns the element using
1000 /// the "emplacer" mechanism. You can pass the returned [`Emplacable<T, _>`]
1001 /// to a function like [`box_new_with`] to get the contained `T`.
1002 ///
1003 /// # Example
1004 ///
1005 /// ```
1006 /// use core::fmt::Debug;
1007 ///
1008 /// use emplacable::{box_new_with, Emplacable};
1009 /// use unsized_vec::{UnsizedVec};
1010 ///
1011 /// let mut vec = UnsizedVec::<dyn Debug>::new();
1012 ///
1013 /// dbg!(vec.is_empty());
1014 /// let nothing: Option<Box<dyn Debug>> = vec.pop_into().map(box_new_with);
1015 /// assert!(nothing.is_none());
1016 ///
1017 /// vec.push_unsize("A beautiful day today");
1018 /// let popped: Option<Box<dyn Debug>> = vec.pop_into().map(box_new_with);
1019 /// let unwrapped: Box<dyn Debug> = popped.unwrap();
1020 /// dbg!(&unwrapped);
1021 ///
1022 /// vec.push_unsize("innit?");
1023 /// dbg!(&vec);
1024 ///
1025 /// let mut popped_emplacable: Emplacable<dyn Debug, _> = vec.pop_into().unwrap();
1026 ///
1027 /// // vec.push_unsize("yea"); // error: cannot borrow `vec` as mutable more than once at a time
1028 /// // The `vec` will remain borrowed until you consume the `Emplacable`!
1029 ///
1030 /// // or we can just drop it...
1031 /// // dropping an `Emplacable` drops
1032 /// // the contained value.
1033 /// popped_emplacable;
1034 ///
1035 /// assert!(vec.is_empty());
1036 ///
1037 /// vec.push_unsize("yea"); // works now
1038 ///
1039 /// ```
1040 ///
1041 /// [`box_new_with`]: emplacable::box_new_with
1042 #[inline]
1043 pub fn pop_into(&mut self) -> Option<Emplacable<T, impl EmplacableFn<T> + '_>> {
1044 if !self.is_empty() {
1045 let closure = move |emplacer: &mut Emplacer<'_, T>| {
1046 // SAFETY: checked above that vec is non-empty
1047 unsafe { self.inner.pop_into_unchecked(emplacer) }
1048 };
1049
1050 // SAFETY: `pop_into_unchecked` upholds the requirements of this closure
1051 Some(unsafe { Emplacable::from_fn(closure) })
1052 } else {
1053 None
1054 }
1055 }
1056
1057 /// Returns the number of elements in the vector, also referred to
1058 /// as its 'length'.
1059 #[must_use]
1060 #[inline]
1061 pub fn len(&self) -> usize {
1062 self.inner.len()
1063 }
1064
1065 /// Returns the number of used bytes in the vector.
1066 #[must_use]
1067 #[inline]
1068 pub fn byte_len(&self) -> usize {
1069 self.inner.byte_len()
1070 }
1071
1072 /// Returns `true` if the vector contains no elements.
1073 #[must_use]
1074 #[inline]
1075 pub fn is_empty(&self) -> bool {
1076 self.len() == 0
1077 }
1078
1079 /// Returns a reference to an element,
1080 /// or `None` if `index` is out of range.
1081 #[must_use]
1082 #[inline]
1083 pub fn get(&self, index: usize) -> Option<&T> {
1084 // SAFETY: Bounds check done right before
1085 (index < self.len()).then(|| unsafe { self.get_unchecked(index) })
1086 }
1087
1088 /// Returns a mutable reference to an element,
1089 /// or `None` if `index` is out of range.
1090 #[must_use]
1091 #[inline]
1092 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
1093 // SAFETY: Bounds check done right before
1094 (index < self.len()).then(|| unsafe { self.get_unchecked_mut(index) })
1095 }
1096
1097 /// Returns a reference to an element, without doing bounds
1098 /// checking.
1099 ///
1100 /// # Safety
1101 ///
1102 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1103 /// even if the resulting reference is not used.
1104 #[must_use]
1105 #[inline]
1106 pub unsafe fn get_unchecked(&self, index: usize) -> &T {
1107 // SAFETY: precondition of function
1108 unsafe { self.inner.get_unchecked_raw(index).as_ref() }
1109 }
1110
1111 /// Returns a mutable reference to an element, without doing bounds
1112 /// checking.
1113 ///
1114 /// # Safety
1115 ///
1116 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1117 /// even if the resulting reference is not used.
1118 #[must_use]
1119 #[inline]
1120 pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
1121 // SAFETY: precondition of function
1122 unsafe { self.inner.get_unchecked_raw(index).as_mut() }
1123 }
1124
1125 /// Returns an iterator over references to the elements of this vec.
1126 #[must_use]
1127 #[inline]
1128 pub fn iter(&self) -> UnsizedIter<'_, T> {
1129 UnsizedIter {
1130 inner: self.inner.iter(),
1131 }
1132 }
1133
1134 /// Returns an iterator over mutable references to the elements of this vec.
1135 #[must_use]
1136 #[inline]
1137 pub fn iter_mut(&mut self) -> UnsizedIterMut<'_, T> {
1138 UnsizedIterMut {
1139 inner: self.inner.iter_mut(),
1140 }
1141 }
1142
1143 /// Coerces this Vec's elements to an unsized type.
1144 ///
1145 /// # Example
1146 ///
1147 /// ```
1148 /// use core::fmt::Debug;
1149 ///
1150 /// use unsized_vec::UnsizedVec;
1151 ///
1152 /// let sized: Vec<u32> = vec![3, 4, 5];
1153 /// let unsize: UnsizedVec<dyn Debug> = UnsizedVec::unsize(sized.into());
1154 /// dbg!(&unsize);
1155 /// ```
1156 #[must_use]
1157 #[inline]
1158 pub fn unsize<U>(self) -> UnsizedVec<U>
1159 where
1160 T: Sized + Unsize<U>,
1161 U: ?Sized,
1162 {
1163 UnsizedVec {
1164 inner: <U as UnsizedVecImpl>::Impl::from_sized(self.inner),
1165 }
1166 }
1167
1168 #[must_use]
1169 #[inline]
1170 fn unused_byte_cap(&self) -> usize {
1171 // SAFETY: len <= cap
1172 unsafe { self.byte_capacity().unchecked_sub(self.byte_len()) }
1173 }
1174}
1175
1176impl<T> Default for UnsizedVec<T>
1177where
1178 T: ?Sized,
1179{
1180 #[inline]
1181 fn default() -> Self {
1182 Self::new()
1183 }
1184}
1185
1186/// The iterator returned by [`UnsizedVec::iter`].
1187#[repr(transparent)]
1188pub struct UnsizedIter<'a, T>
1189where
1190 T: ?Sized + 'a,
1191{
1192 inner: <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::Iter<'a>,
1193}
1194
1195/// The iterator returned by [`UnsizedVec::iter_mut`].
1196#[repr(transparent)]
1197pub struct UnsizedIterMut<'a, T>
1198where
1199 T: ?Sized + 'a,
1200{
1201 inner: <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::IterMut<'a>,
1202}
1203
1204impl<T> From<::alloc::vec::Vec<T>> for UnsizedVec<T> {
1205 #[inline]
1206 fn from(value: ::alloc::vec::Vec<T>) -> Self {
1207 UnsizedVec { inner: value }
1208 }
1209}
1210
1211impl<T> From<UnsizedVec<T>> for ::alloc::vec::Vec<T> {
1212 #[inline]
1213 fn from(value: UnsizedVec<T>) -> Self {
1214 value.inner
1215 }
1216}
1217
1218impl<T> Index<usize> for UnsizedVec<T>
1219where
1220 T: ?Sized,
1221{
1222 type Output = T;
1223
1224 #[inline]
1225 fn index(&self, index: usize) -> &Self::Output {
1226 self.get(index).expect("index out of range")
1227 }
1228}
1229
1230impl<T> IndexMut<usize> for UnsizedVec<T>
1231where
1232 T: ?Sized,
1233{
1234 #[inline]
1235 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1236 self.get_mut(index).expect("index out of range")
1237 }
1238}
1239
1240impl<'a, T> From<core::slice::Iter<'a, T>> for UnsizedIter<'a, T>
1241where
1242 T: 'a,
1243{
1244 #[inline]
1245 fn from(value: core::slice::Iter<'a, T>) -> Self {
1246 UnsizedIter { inner: value }
1247 }
1248}
1249
1250impl<'a, T> From<UnsizedIter<'a, T>> for core::slice::Iter<'a, T>
1251where
1252 T: 'a,
1253{
1254 #[inline]
1255 fn from(value: UnsizedIter<'a, T>) -> Self {
1256 value.inner
1257 }
1258}
1259
1260macro_rules! iter_ref {
1261 ($iter_ty:ident $($muta:ident)?) => {
1262 impl<'a, T> Iterator for $iter_ty<'a, T>
1263 where
1264 T: ?Sized + 'a,
1265 {
1266 type Item = &'a $($muta)? T;
1267
1268 #[inline]
1269 fn next(&mut self) -> Option<Self::Item> {
1270 self.inner.next()
1271 }
1272
1273 #[inline]
1274 fn size_hint(&self) -> (usize, Option<usize>) {
1275 self.inner.size_hint()
1276 }
1277
1278 #[inline]
1279 fn count(self) -> usize {
1280 self.inner.count()
1281 }
1282
1283 #[inline]
1284 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1285 self.inner.nth(n)
1286 }
1287
1288 #[inline]
1289 fn last(self) -> Option<Self::Item> {
1290 self.inner.last()
1291 }
1292
1293 #[inline]
1294 fn for_each<F>(self, f: F)
1295 where
1296 F: FnMut(Self::Item),
1297 {
1298 self.inner.for_each(f);
1299 }
1300
1301 #[inline]
1302 fn all<F>(&mut self, f: F) -> bool
1303 where
1304 F: FnMut(Self::Item) -> bool,
1305 {
1306 self.inner.all(f)
1307 }
1308
1309 #[inline]
1310 fn any<F>(&mut self, f: F) -> bool
1311 where
1312 F: FnMut(Self::Item) -> bool,
1313 {
1314 self.inner.any(f)
1315 }
1316
1317 #[inline]
1318 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
1319 where
1320 P: FnMut(&Self::Item) -> bool,
1321 {
1322 self.inner.find(predicate)
1323 }
1324
1325 #[inline]
1326 fn find_map<B, F>(&mut self, f: F) -> Option<B>
1327 where
1328 F: FnMut(Self::Item) -> Option<B>,
1329 {
1330 self.inner.find_map(f)
1331 }
1332
1333 #[inline]
1334 fn position<P>(&mut self, predicate: P) -> Option<usize>
1335 where
1336 P: FnMut(Self::Item) -> bool,
1337 {
1338 self.inner.position(predicate)
1339 }
1340 }
1341
1342 impl<'a, T> DoubleEndedIterator for $iter_ty<'a, T>
1343 where
1344 T: ?Sized + 'a,
1345 {
1346 #[inline]
1347 fn next_back(&mut self) -> Option<Self::Item> {
1348 self.inner.next_back()
1349 }
1350
1351 #[inline]
1352 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1353 self.inner.nth_back(n)
1354 }
1355 }
1356
1357 impl<'a, T> ExactSizeIterator for $iter_ty<'a, T>
1358 where
1359 T: ?Sized + 'a,
1360 {}
1361 impl<'a, T> FusedIterator for $iter_ty<'a, T>
1362 where
1363 T: ?Sized + 'a,
1364 {}
1365 }
1366}
1367
1368iter_ref!(UnsizedIter);
1369iter_ref!(UnsizedIterMut mut);
1370
1371impl<'a, T> IntoIterator for &'a UnsizedVec<T>
1372where
1373 T: ?Sized + 'a,
1374{
1375 type Item = &'a T;
1376
1377 type IntoIter = UnsizedIter<'a, T>;
1378
1379 #[inline]
1380 fn into_iter(self) -> Self::IntoIter {
1381 self.iter()
1382 }
1383}
1384
1385impl<'a, T> IntoIterator for &'a mut UnsizedVec<T>
1386where
1387 T: ?Sized + 'a,
1388{
1389 type Item = &'a mut T;
1390
1391 type IntoIter = UnsizedIterMut<'a, T>;
1392
1393 #[inline]
1394 fn into_iter(self) -> Self::IntoIter {
1395 self.iter_mut()
1396 }
1397}
1398
1399impl<T, F> FromIterator<Emplacable<T, F>> for UnsizedVec<T>
1400where
1401 T: ?Sized,
1402 F: EmplacableFn<T>,
1403{
1404 #[inline]
1405 fn from_iter<I>(iter: I) -> Self
1406 where
1407 I: IntoIterator<Item = Emplacable<T, F>>,
1408 {
1409 let mut vec = UnsizedVec::new();
1410 vec.extend(iter);
1411 vec
1412 }
1413}
1414
1415impl<T, F> Extend<Emplacable<T, F>> for UnsizedVec<T>
1416where
1417 T: ?Sized,
1418 F: EmplacableFn<T>,
1419{
1420 #[inline]
1421 fn extend<I>(&mut self, iter: I)
1422 where
1423 I: IntoIterator<Item = Emplacable<T, F>>,
1424 {
1425 fn extend_inner<T: ?Sized, F: EmplacableFn<T>, I: Iterator<Item = Emplacable<T, F>>>(
1426 vec: &mut UnsizedVec<T>,
1427 iter: I,
1428 ) {
1429 vec.reserve_exact(iter.size_hint().0);
1430 for emplacable in iter {
1431 vec.push_with(emplacable);
1432 }
1433 }
1434
1435 extend_inner(self, iter.into_iter());
1436 }
1437}
1438
1439impl<T> Debug for UnsizedVec<T>
1440where
1441 T: ?Sized + Debug,
1442{
1443 #[inline]
1444 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1445 f.debug_list().entries(self.iter()).finish()
1446 }
1447}
1448
1449impl<T> Clone for UnsizedVec<T>
1450where
1451 T: Clone,
1452{
1453 #[inline]
1454 fn clone(&self) -> Self {
1455 let mut ret = UnsizedVec::with_capacity_bytes_align(
1456 self.capacity(),
1457 self.byte_capacity(),
1458 self.align(),
1459 );
1460 for elem in self {
1461 ret.push(elem.clone());
1462 }
1463 ret
1464 }
1465}
1466
1467impl<T, U> PartialEq<UnsizedVec<U>> for UnsizedVec<T>
1468where
1469 T: ?Sized + PartialEq<U>,
1470 U: ?Sized,
1471{
1472 #[inline]
1473 fn eq(&self, other: &UnsizedVec<U>) -> bool {
1474 self.len() == other.len() && self.iter().zip(other).all(|(l, r)| l == r)
1475 }
1476}
1477
1478impl<T> Eq for UnsizedVec<T> where T: ?Sized + Eq {}
1479
1480impl<T, U> PartialOrd<UnsizedVec<U>> for UnsizedVec<T>
1481where
1482 T: ?Sized + PartialOrd<U>,
1483 U: ?Sized,
1484{
1485 fn partial_cmp(&self, other: &UnsizedVec<U>) -> Option<cmp::Ordering> {
1486 for (l, r) in self.iter().zip(other) {
1487 match l.partial_cmp(r) {
1488 Some(cmp::Ordering::Equal) => (),
1489 res => return res,
1490 }
1491 }
1492 self.len().partial_cmp(&other.len())
1493 }
1494}
1495
1496impl<T> Ord for UnsizedVec<T>
1497where
1498 T: ?Sized + Ord,
1499{
1500 #[inline]
1501 fn cmp(&self, other: &Self) -> cmp::Ordering {
1502 for (l, r) in self.iter().zip(other) {
1503 match l.cmp(r) {
1504 cmp::Ordering::Equal => (),
1505 res => return res,
1506 }
1507 }
1508 self.len().cmp(&other.len())
1509 }
1510}
1511
1512impl<T> Hash for UnsizedVec<T>
1513where
1514 T: ?Sized + Hash,
1515{
1516 #[inline]
1517 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
1518 for elem in self {
1519 elem.hash(state);
1520 }
1521 }
1522}
1523
1524#[cfg(feature = "serde")]
1525use serde::{Serialize, ser::SerializeSeq};
1526
1527#[cfg(feature = "serde")]
1528impl<T> Serialize for UnsizedVec<T>
1529where
1530 T: ?Sized + Serialize,
1531{
1532 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1533 where
1534 S: serde::Serializer,
1535 {
1536 let mut elem_serialize = serializer.serialize_seq(Some(self.len()))?;
1537 for elem in self {
1538 elem_serialize.serialize_element(elem)?;
1539 }
1540 elem_serialize.end()
1541 }
1542}
1543
1544/// Impementation detail of `unsized_vec` macro.
1545#[doc(hidden)]
1546pub trait PushToUnsizedVec<U: ?Sized> {
1547 fn push_to_unsized_vec(self, vec: &mut UnsizedVec<U>);
1548}
1549
1550impl<T: ?Sized> PushToUnsizedVec<T> for T {
1551 #[inline]
1552 fn push_to_unsized_vec(self, vec: &mut UnsizedVec<T>) {
1553 vec.push(self);
1554 }
1555}
1556
1557impl<T: ?Sized, F: EmplacableFn<T>> PushToUnsizedVec<T> for Emplacable<T, F> {
1558 #[inline]
1559 fn push_to_unsized_vec(self, vec: &mut UnsizedVec<T>) {
1560 vec.push_with(self);
1561 }
1562}
1563
1564/// Like the standard library's [`vec`] macro.
1565/// Accepts both raw unsized `T`s and
1566/// [`Emplacable<T,_>`]s.
1567///
1568/// However, this does not accept sized values implementing
1569/// [`Unsize<T>`]; you can use [`unsize_vec`] for that.
1570///
1571/// # Example
1572///
1573/// ```
1574/// #![allow(internal_features)] // for `unsized_fn_params`
1575/// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
1576///
1577/// use emplacable::unsize;
1578/// use unsized_vec::{UnsizedVec, unsized_vec};
1579///
1580/// let my_vec = unsized_vec![[23_u32, 17], [16, 34], [23, 47]];
1581///
1582/// let mut my_vec_unsized: UnsizedVec<[u32]> = my_vec.unsize();
1583///
1584/// let another_vec = unsized_vec![unsize!([42], ([u32; 1]) -> [u32]), my_vec_unsized.remove_into(2)];
1585/// ```
1586///
1587/// [`vec`]: macro@alloc::vec
1588#[macro_export]
1589macro_rules! unsized_vec {
1590 () => (
1591 $crate::UnsizedVec::new()
1592 );
1593 ($($x:expr),+ $(,)?) => (
1594 {
1595 let mut ret = $crate::UnsizedVec::new();
1596 $($crate::PushToUnsizedVec::push_to_unsized_vec($x, &mut ret);)+
1597 ret
1598 }
1599 );
1600}
1601
1602/// Like [`unsized_vec`], but unsizes its arguments
1603/// using the [`Unsize`] trait.
1604///
1605/// Accepts sized values that can coerce to an unsized `T`.
1606/// If you have raw unsized `T`s or [`Emplacable<T,_>`]s,
1607/// use [`unsized_vec`] instead.
1608///
1609/// # Example
1610///
1611/// ```
1612/// use core::fmt::Debug;
1613///
1614/// use unsized_vec::{unsize_vec, UnsizedVec};
1615///
1616/// let my_vec: UnsizedVec<dyn Debug> = unsize_vec![1, "hello!", 97.5];
1617/// ```
1618#[macro_export]
1619macro_rules! unsize_vec {
1620 () => (
1621 $crate::UnsizedVec::new()
1622 );
1623 ($($x:expr),+ $(,)?) => (
1624 {
1625 let mut ret = $crate::UnsizedVec::new();
1626 $(ret.push_unsize($x);)+
1627 ret
1628 }
1629 );
1630}