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