rkyv/util/
aligned_vec.rs

1use crate::vec::VecResolver;
2use crate::{
3    ser::{ScratchSpace, Serializer},
4    vec::ArchivedVec,
5    Archive, Archived, Serialize,
6};
7
8#[cfg(not(feature = "std"))]
9use ::alloc::{alloc, boxed::Box, vec::Vec};
10use core::borrow::{Borrow, BorrowMut};
11use core::{
12    fmt,
13    ops::{Deref, DerefMut, Index, IndexMut},
14    ptr::NonNull,
15    slice,
16};
17#[cfg(feature = "std")]
18use std::{alloc, io};
19
20/// A vector of bytes that aligns its memory to 16 bytes.
21///
22/// The alignment also applies to `ArchivedAlignedVec`, which is useful for aligning opaque bytes inside of an archived data
23/// type.
24///
25/// ```
26/// # use rkyv::{archived_value, AlignedBytes, AlignedVec, Archive, Serialize};
27/// # use rkyv::ser::Serializer;
28/// # use rkyv::ser::serializers::CoreSerializer;
29/// #
30/// #[derive(Archive, Serialize)]
31/// struct HasAlignedBytes {
32///     pub bytes: AlignedVec,
33/// }
34///
35/// let mut serializer = CoreSerializer::<256, 0>::default();
36///
37/// // Write a single byte to force re-alignment.
38/// serializer.write(&[0]).unwrap();
39/// assert_eq!(serializer.pos(), 1);
40///
41/// let mut bytes = AlignedVec::new();
42/// bytes.extend_from_slice(&[1, 2, 3]);
43/// let pos = serializer.serialize_value(&HasAlignedBytes { bytes }).unwrap();
44///
45/// // Make sure we can recover the archived type with the expected alignment.
46/// let buf = serializer.into_serializer().into_inner();
47/// let archived = unsafe { archived_value::<HasAlignedBytes>(buf.as_ref(), pos) };
48/// assert_eq!(archived.bytes.as_slice(), &[1, 2, 3]);
49/// assert_eq!(archived.bytes.as_ptr().align_offset(16), 0);
50/// ```
51pub struct AlignedVec {
52    ptr: NonNull<u8>,
53    cap: usize,
54    len: usize,
55}
56
57impl Drop for AlignedVec {
58    #[inline]
59    fn drop(&mut self) {
60        if self.cap != 0 {
61            unsafe {
62                alloc::dealloc(self.ptr.as_ptr(), self.layout());
63            }
64        }
65    }
66}
67
68impl AlignedVec {
69    /// The alignment of the vector
70    pub const ALIGNMENT: usize = 16;
71
72    /// Maximum capacity of the vector.
73    /// Dictated by the requirements of
74    /// [`alloc::Layout`](https://doc.rust-lang.org/alloc/alloc/struct.Layout.html).
75    /// "`size`, when rounded up to the nearest multiple of `align`, must not overflow `isize`
76    /// (i.e. the rounded value must be less than or equal to `isize::MAX`)".
77    pub const MAX_CAPACITY: usize = isize::MAX as usize - (Self::ALIGNMENT - 1);
78
79    /// Constructs a new, empty `AlignedVec`.
80    ///
81    /// The vector will not allocate until elements are pushed into it.
82    ///
83    /// # Examples
84    /// ```
85    /// use rkyv::AlignedVec;
86    ///
87    /// let mut vec = AlignedVec::new();
88    /// ```
89    #[inline]
90    pub fn new() -> Self {
91        AlignedVec {
92            ptr: NonNull::dangling(),
93            cap: 0,
94            len: 0,
95        }
96    }
97
98    /// Constructs a new, empty `AlignedVec` with the specified capacity.
99    ///
100    /// The vector will be able to hold exactly `capacity` bytes without reallocating. If
101    /// `capacity` is 0, the vector will not allocate.
102    ///
103    /// # Examples
104    /// ```
105    /// use rkyv::AlignedVec;
106    ///
107    /// let mut vec = AlignedVec::with_capacity(10);
108    ///
109    /// // The vector contains no items, even though it has capacity for more
110    /// assert_eq!(vec.len(), 0);
111    /// assert_eq!(vec.capacity(), 10);
112    ///
113    /// // These are all done without reallocating...
114    /// for i in 0..10 {
115    ///     vec.push(i);
116    /// }
117    /// assert_eq!(vec.len(), 10);
118    /// assert_eq!(vec.capacity(), 10);
119    ///
120    /// // ...but this may make the vector reallocate
121    /// vec.push(11);
122    /// assert_eq!(vec.len(), 11);
123    /// assert!(vec.capacity() >= 11);
124    /// ```
125    #[inline]
126    pub fn with_capacity(capacity: usize) -> Self {
127        if capacity == 0 {
128            Self::new()
129        } else {
130            assert!(
131                capacity <= Self::MAX_CAPACITY,
132                "`capacity` cannot exceed isize::MAX - 15"
133            );
134            let ptr = unsafe {
135                let layout = alloc::Layout::from_size_align_unchecked(capacity, Self::ALIGNMENT);
136                let ptr = alloc::alloc(layout);
137                if ptr.is_null() {
138                    alloc::handle_alloc_error(layout);
139                }
140                NonNull::new_unchecked(ptr)
141            };
142            Self {
143                ptr,
144                cap: capacity,
145                len: 0,
146            }
147        }
148    }
149
150    #[inline]
151    fn layout(&self) -> alloc::Layout {
152        unsafe { alloc::Layout::from_size_align_unchecked(self.cap, Self::ALIGNMENT) }
153    }
154
155    /// Clears the vector, removing all values.
156    ///
157    /// Note that this method has no effect on the allocated capacity of the vector.
158    ///
159    /// # Examples
160    /// ```
161    /// use rkyv::AlignedVec;
162    ///
163    /// let mut v = AlignedVec::new();
164    /// v.extend_from_slice(&[1, 2, 3, 4]);
165    ///
166    /// v.clear();
167    ///
168    /// assert!(v.is_empty());
169    /// ```
170    #[inline]
171    pub fn clear(&mut self) {
172        self.len = 0;
173    }
174
175    /// Change capacity of vector.
176    ///
177    /// Will set capacity to exactly `new_cap`.
178    /// Can be used to either grow or shrink capacity.
179    /// Backing memory will be reallocated.
180    ///
181    /// Usually the safe methods `reserve` or `reserve_exact` are a better choice.
182    /// This method only exists as a micro-optimization for very performance-sensitive
183    /// code where where the calculation of capacity required has already been
184    /// performed, and you want to avoid doing it again, or if you want to implement
185    /// a different growth strategy.
186    ///
187    /// # Safety
188    ///
189    /// - `new_cap` must be less than or equal to [`MAX_CAPACITY`](AlignedVec::MAX_CAPACITY)
190    /// - `new_cap` must be greater than or equal to [`len()`](AlignedVec::len)
191    #[inline]
192    pub unsafe fn change_capacity(&mut self, new_cap: usize) {
193        debug_assert!(new_cap <= Self::MAX_CAPACITY);
194        debug_assert!(new_cap >= self.len);
195
196        if new_cap > 0 {
197            let new_ptr = if self.cap > 0 {
198                let new_ptr = alloc::realloc(self.ptr.as_ptr(), self.layout(), new_cap);
199                if new_ptr.is_null() {
200                    alloc::handle_alloc_error(alloc::Layout::from_size_align_unchecked(
201                        new_cap,
202                        Self::ALIGNMENT,
203                    ));
204                }
205                new_ptr
206            } else {
207                let layout = alloc::Layout::from_size_align_unchecked(new_cap, Self::ALIGNMENT);
208                let new_ptr = alloc::alloc(layout);
209                if new_ptr.is_null() {
210                    alloc::handle_alloc_error(layout);
211                }
212                new_ptr
213            };
214            self.ptr = NonNull::new_unchecked(new_ptr);
215            self.cap = new_cap;
216        } else if self.cap > 0 {
217            alloc::dealloc(self.ptr.as_ptr(), self.layout());
218            self.ptr = NonNull::dangling();
219            self.cap = 0;
220        }
221    }
222
223    /// Shrinks the capacity of the vector as much as possible.
224    ///
225    /// It will drop down as close as possible to the length but the allocator may still inform the
226    /// vector that there is space for a few more elements.
227    ///
228    /// # Examples
229    /// ```
230    /// use rkyv::AlignedVec;
231    ///
232    /// let mut vec = AlignedVec::with_capacity(10);
233    /// vec.extend_from_slice(&[1, 2, 3]);
234    /// assert_eq!(vec.capacity(), 10);
235    /// vec.shrink_to_fit();
236    /// assert!(vec.capacity() >= 3);
237    ///
238    /// vec.clear();
239    /// vec.shrink_to_fit();
240    /// assert!(vec.capacity() == 0);
241    /// ```
242    #[inline]
243    pub fn shrink_to_fit(&mut self) {
244        if self.cap != self.len {
245            // New capacity cannot exceed max as it's shrinking
246            unsafe { self.change_capacity(self.len) };
247        }
248    }
249
250    /// Returns an unsafe mutable pointer to the vector's buffer.
251    ///
252    /// The caller must ensure that the vector outlives the pointer this function returns, or else
253    /// it will end up pointing to garbage. Modifying the vector may cause its buffer to be
254    /// reallocated, which would also make any pointers to it invalid.
255    ///
256    /// # Examples
257    /// ```
258    /// use rkyv::AlignedVec;
259    ///
260    /// // Allocate vecotr big enough for 4 bytes.
261    /// let size = 4;
262    /// let mut x = AlignedVec::with_capacity(size);
263    /// let x_ptr = x.as_mut_ptr();
264    ///
265    /// // Initialize elements via raw pointer writes, then set length.
266    /// unsafe {
267    ///     for i in 0..size {
268    ///         *x_ptr.add(i) = i as u8;
269    ///     }
270    ///     x.set_len(size);
271    /// }
272    /// assert_eq!(&*x, &[0, 1, 2, 3]);
273    /// ```
274    #[inline]
275    pub fn as_mut_ptr(&mut self) -> *mut u8 {
276        self.ptr.as_ptr()
277    }
278
279    /// Extracts a mutable slice of the entire vector.
280    ///
281    /// Equivalent to `&mut s[..]`.
282    ///
283    /// # Examples
284    /// ```
285    /// use rkyv::AlignedVec;
286    ///
287    /// let mut vec = AlignedVec::new();
288    /// vec.extend_from_slice(&[1, 2, 3, 4, 5]);
289    /// assert_eq!(vec.as_mut_slice().len(), 5);
290    /// for i in 0..5 {
291    ///     assert_eq!(vec.as_mut_slice()[i], i as u8 + 1);
292    ///     vec.as_mut_slice()[i] = i as u8;
293    ///     assert_eq!(vec.as_mut_slice()[i], i as u8);
294    /// }
295    /// ```
296    #[inline]
297    pub fn as_mut_slice(&mut self) -> &mut [u8] {
298        unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
299    }
300
301    /// Returns a raw pointer to the vector's buffer.
302    ///
303    /// The caller must ensure that the vector outlives the pointer this function returns, or else
304    /// it will end up pointing to garbage. Modifying the vector may cause its buffer to be
305    /// reallocated, which would also make any pointers to it invalid.
306    ///
307    /// The caller must also ensure that the memory the pointer (non-transitively) points to is
308    /// never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived
309    /// from it. If you need to mutate the contents of the slice, use
310    /// [`as_mut_ptr`](AlignedVec::as_mut_ptr).
311    ///
312    /// # Examples
313    /// ```
314    /// use rkyv::AlignedVec;
315    ///
316    /// let mut x = AlignedVec::new();
317    /// x.extend_from_slice(&[1, 2, 4]);
318    /// let x_ptr = x.as_ptr();
319    ///
320    /// unsafe {
321    ///     for i in 0..x.len() {
322    ///         assert_eq!(*x_ptr.add(i), 1 << i);
323    ///     }
324    /// }
325    /// ```
326    #[inline]
327    pub fn as_ptr(&self) -> *const u8 {
328        self.ptr.as_ptr()
329    }
330
331    /// Extracts a slice containing the entire vector.
332    ///
333    /// Equivalent to `&s[..]`.
334    ///
335    /// # Examples
336    /// ```
337    /// use rkyv::AlignedVec;
338    ///
339    /// let mut vec = AlignedVec::new();
340    /// vec.extend_from_slice(&[1, 2, 3, 4, 5]);
341    /// assert_eq!(vec.as_slice().len(), 5);
342    /// for i in 0..5 {
343    ///     assert_eq!(vec.as_slice()[i], i as u8 + 1);
344    /// }
345    /// ```
346    #[inline]
347    pub fn as_slice(&self) -> &[u8] {
348        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
349    }
350
351    /// Returns the number of elements the vector can hold without reallocating.
352    ///
353    /// # Examples
354    /// ```
355    /// use rkyv::AlignedVec;
356    ///
357    /// let vec = AlignedVec::with_capacity(10);
358    /// assert_eq!(vec.capacity(), 10);
359    /// ```
360    #[inline]
361    pub fn capacity(&self) -> usize {
362        self.cap
363    }
364
365    /// Reserves capacity for at least `additional` more bytes to be inserted into the given
366    /// `AlignedVec`. The collection may reserve more space to avoid frequent reallocations. After
367    /// calling `reserve`, capacity will be greater than or equal to `self.len() + additional`. Does
368    /// nothing if capacity is already sufficient.
369    ///
370    /// # Panics
371    ///
372    /// Panics if the new capacity exceeds `isize::MAX - 15` bytes.
373    ///
374    /// # Examples
375    /// ```
376    /// use rkyv::AlignedVec;
377    ///
378    /// let mut vec = AlignedVec::new();
379    /// vec.push(1);
380    /// vec.reserve(10);
381    /// assert!(vec.capacity() >= 11);
382    /// ```
383    #[inline]
384    pub fn reserve(&mut self, additional: usize) {
385        // Cannot wrap because capacity always exceeds len,
386        // but avoids having to handle potential overflow here
387        let remaining = self.cap.wrapping_sub(self.len);
388        if additional > remaining {
389            self.do_reserve(additional);
390        }
391    }
392
393    /// Extend capacity after `reserve` has found it's necessary.
394    ///
395    /// Actually performing the extension is in this separate function marked
396    /// `#[cold]` to hint to compiler that this branch is not often taken.
397    /// This keeps the path for common case where capacity is already sufficient
398    /// as fast as possible, and makes `reserve` more likely to be inlined.
399    /// This is the same trick that Rust's `Vec::reserve` uses.
400    #[cold]
401    fn do_reserve(&mut self, additional: usize) {
402        let new_cap = self
403            .len
404            .checked_add(additional)
405            .expect("cannot reserve a larger AlignedVec");
406        unsafe { self.grow_capacity_to(new_cap) };
407    }
408
409    /// Grows total capacity of vector to `new_cap` or more.
410    ///
411    /// Capacity after this call will be `new_cap` rounded up to next power of 2,
412    /// unless that would exceed maximum capacity, in which case capacity
413    /// is capped at the maximum.
414    ///
415    /// This is same growth strategy used by `reserve`, `push` and `extend_from_slice`.
416    ///
417    /// Usually the safe methods `reserve` or `reserve_exact` are a better choice.
418    /// This method only exists as a micro-optimization for very performance-sensitive
419    /// code where where the calculation of capacity required has already been
420    /// performed, and you want to avoid doing it again.
421    ///
422    /// Maximum capacity is `isize::MAX - 15` bytes.
423    ///
424    /// # Panics
425    ///
426    /// Panics if `new_cap` exceeds `isize::MAX - 15` bytes.
427    ///
428    /// # Safety
429    ///
430    /// - `new_cap` must be greater than current [`capacity()`](AlignedVec::capacity)
431    ///
432    /// # Examples
433    /// ```
434    /// use rkyv::AlignedVec;
435    ///
436    /// let mut vec = AlignedVec::new();
437    /// vec.push(1);
438    /// unsafe { vec.grow_capacity_to(50) };
439    /// assert_eq!(vec.len(), 1);
440    /// assert_eq!(vec.capacity(), 64);
441    /// ```
442    #[inline]
443    pub unsafe fn grow_capacity_to(&mut self, new_cap: usize) {
444        debug_assert!(new_cap > self.cap);
445
446        let new_cap = if new_cap > (isize::MAX as usize + 1) >> 1 {
447            // Rounding up to next power of 2 would result in `isize::MAX + 1` or higher,
448            // which exceeds max capacity. So cap at max instead.
449            assert!(
450                new_cap <= Self::MAX_CAPACITY,
451                "cannot reserve a larger AlignedVec"
452            );
453            Self::MAX_CAPACITY
454        } else {
455            // Cannot overflow due to check above
456            new_cap.next_power_of_two()
457        };
458        self.change_capacity(new_cap);
459    }
460
461    /// Resizes the Vec in-place so that len is equal to new_len.
462    ///
463    /// If new_len is greater than len, the Vec is extended by the difference, with each additional slot filled with value. If new_len is less than len, the Vec is simply truncated.
464    ///
465    /// # Panics
466    ///
467    /// Panics if the new length exceeds `isize::MAX - 15` bytes.
468    ///
469    /// # Examples
470    /// ```
471    /// use rkyv::AlignedVec;
472    ///
473    /// let mut vec = AlignedVec::new();
474    /// vec.push(3);
475    /// vec.resize(3, 2);
476    /// assert_eq!(vec.as_slice(), &[3, 2, 2]);
477    ///
478    /// let mut vec = AlignedVec::new();
479    /// vec.extend_from_slice(&[1, 2, 3, 4]);
480    /// vec.resize(2, 0);
481    /// assert_eq!(vec.as_slice(), &[1, 2]);
482    /// ```
483    #[inline]
484    pub fn resize(&mut self, new_len: usize, value: u8) {
485        if new_len > self.len {
486            let additional = new_len - self.len;
487            self.reserve(additional);
488            unsafe {
489                core::ptr::write_bytes(self.ptr.as_ptr().add(self.len), value, additional);
490            }
491        }
492        unsafe {
493            self.set_len(new_len);
494        }
495    }
496
497    /// Returns `true` if the vector contains no elements.
498    ///
499    /// # Examples
500    /// ```
501    /// use rkyv::AlignedVec;
502    ///
503    /// let mut v = Vec::new();
504    /// assert!(v.is_empty());
505    ///
506    /// v.push(1);
507    /// assert!(!v.is_empty());
508    /// ```
509    #[inline]
510    pub fn is_empty(&self) -> bool {
511        self.len == 0
512    }
513
514    /// Returns the number of elements in the vector, also referred to as its 'length'.
515    ///
516    /// # Examples
517    /// ```
518    /// use rkyv::AlignedVec;
519    ///
520    /// let mut a = AlignedVec::new();
521    /// a.extend_from_slice(&[1, 2, 3]);
522    /// assert_eq!(a.len(), 3);
523    /// ```
524    #[inline]
525    pub fn len(&self) -> usize {
526        self.len
527    }
528
529    /// Copies and appends all bytes in a slice to the `AlignedVec`.
530    ///
531    /// The elements of the slice are appended in-order.
532    ///
533    /// # Examples
534    /// ```
535    /// use rkyv::AlignedVec;
536    ///
537    /// let mut vec = AlignedVec::new();
538    /// vec.push(1);
539    /// vec.extend_from_slice(&[2, 3, 4]);
540    /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4]);
541    /// ```
542    #[inline]
543    pub fn extend_from_slice(&mut self, other: &[u8]) {
544        if !other.is_empty() {
545            self.reserve(other.len());
546            unsafe {
547                core::ptr::copy_nonoverlapping(
548                    other.as_ptr(),
549                    self.as_mut_ptr().add(self.len()),
550                    other.len(),
551                );
552            }
553            self.len += other.len();
554        }
555    }
556
557    /// Removes the last element from a vector and returns it, or `None` if it is empty.
558    ///
559    /// # Examples
560    /// ```
561    /// use rkyv::AlignedVec;
562    ///
563    /// let mut vec = AlignedVec::new();
564    /// vec.extend_from_slice(&[1, 2, 3]);
565    /// assert_eq!(vec.pop(), Some(3));
566    /// assert_eq!(vec.as_slice(), &[1, 2]);
567    /// ```
568    #[inline]
569    pub fn pop(&mut self) -> Option<u8> {
570        if self.len == 0 {
571            None
572        } else {
573            let result = self[self.len - 1];
574            self.len -= 1;
575            Some(result)
576        }
577    }
578
579    /// Appends an element to the back of a collection.
580    ///
581    /// # Panics
582    ///
583    /// Panics if the new capacity exceeds `isize::MAX - 15` bytes.
584    ///
585    /// # Examples
586    /// ```
587    /// use rkyv::AlignedVec;
588    ///
589    /// let mut vec = AlignedVec::new();
590    /// vec.extend_from_slice(&[1, 2]);
591    /// vec.push(3);
592    /// assert_eq!(vec.as_slice(), &[1, 2, 3]);
593    /// ```
594    #[inline]
595    pub fn push(&mut self, value: u8) {
596        if self.len == self.cap {
597            self.reserve_for_push();
598        }
599
600        unsafe {
601            self.as_mut_ptr().add(self.len).write(value);
602            self.len += 1;
603        }
604    }
605
606    /// Extend capacity by at least 1 byte after `push` has found it's necessary.
607    ///
608    /// Actually performing the extension is in this separate function marked
609    /// `#[cold]` to hint to compiler that this branch is not often taken.
610    /// This keeps the path for common case where capacity is already sufficient
611    /// as fast as possible, and makes `push` more likely to be inlined.
612    /// This is the same trick that Rust's `Vec::push` uses.
613    #[cold]
614    fn reserve_for_push(&mut self) {
615        // `len` is always less than `isize::MAX`, so no possibility of overflow here
616        let new_cap = self.len + 1;
617        unsafe { self.grow_capacity_to(new_cap) };
618    }
619
620    /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
621    /// given `AlignedVec`. After calling `reserve_exact`, capacity will be greater than or equal
622    /// to `self.len() + additional`. Does nothing if the capacity is already sufficient.
623    ///
624    /// Note that the allocator may give the collection more space than it requests. Therefore,
625    /// capacity can not be relied upon to be precisely minimal. Prefer reserve if future insertions
626    /// are expected.
627    ///
628    /// # Panics
629    ///
630    /// Panics if the new capacity overflows `isize::MAX - 15`.
631    ///
632    /// # Examples
633    /// ```
634    /// use rkyv::AlignedVec;
635    ///
636    /// let mut vec = AlignedVec::new();
637    /// vec.push(1);
638    /// vec.reserve_exact(10);
639    /// assert!(vec.capacity() >= 11);
640    /// ```
641    #[inline]
642    pub fn reserve_exact(&mut self, additional: usize) {
643        // This function does not use the hot/cold paths trick that `reserve`
644        // and `push` do, on assumption that user probably knows this will require
645        // an increase in capacity. Otherwise, they'd likely use `reserve`.
646        let new_cap = self
647            .len
648            .checked_add(additional)
649            .expect("cannot reserve a larger AlignedVec");
650        if new_cap > self.cap {
651            assert!(
652                new_cap <= Self::MAX_CAPACITY,
653                "cannot reserve a larger AlignedVec"
654            );
655            unsafe { self.change_capacity(new_cap) };
656        }
657    }
658
659    /// Forces the length of the vector to `new_len`.
660    ///
661    /// This is a low-level operation that maintains none of the normal invariants of the type.
662    ///
663    /// # Safety
664    ///
665    /// - `new_len` must be less than or equal to [`capacity()`](AlignedVec::capacity)
666    /// - The elements at `old_len..new_len` must be initialized
667    ///
668    /// # Examples
669    /// ```
670    /// use rkyv::AlignedVec;
671    ///
672    /// let mut vec = AlignedVec::with_capacity(3);
673    /// vec.extend_from_slice(&[1, 2, 3]);
674    ///
675    /// // SAFETY:
676    /// // 1. `old_len..0` is empty to no elements need to be initialized.
677    /// // 2. `0 <= capacity` always holds whatever capacity is.
678    /// unsafe {
679    ///     vec.set_len(0);
680    /// }
681    /// ```
682    #[inline]
683    pub unsafe fn set_len(&mut self, new_len: usize) {
684        debug_assert!(new_len <= self.capacity());
685
686        self.len = new_len;
687    }
688
689    /// Converts the vector into `Box<[u8]>`.
690    ///
691    /// This method reallocates and copies the underlying bytes. Any excess capacity is dropped.
692    ///
693    /// # Examples
694    /// ```
695    /// use rkyv::AlignedVec;
696    ///
697    /// let mut v = AlignedVec::new();
698    /// v.extend_from_slice(&[1, 2, 3]);
699    ///
700    /// let slice = v.into_boxed_slice();
701    /// ```
702    ///
703    /// Any excess capacity is removed:
704    ///
705    /// ```
706    /// use rkyv::AlignedVec;
707    ///
708    /// let mut vec = AlignedVec::with_capacity(10);
709    /// vec.extend_from_slice(&[1, 2, 3]);
710    ///
711    /// assert_eq!(vec.capacity(), 10);
712    /// let slice = vec.into_boxed_slice();
713    /// assert_eq!(slice.len(), 3);
714    /// ```
715    #[inline]
716    pub fn into_boxed_slice(self) -> Box<[u8]> {
717        self.into_vec().into_boxed_slice()
718    }
719
720    /// Converts the vector into `Vec<u8>`.
721    ///
722    /// This method reallocates and copies the underlying bytes. Any excess capacity is dropped.
723    ///
724    /// # Examples
725    /// ```
726    /// use rkyv::AlignedVec;
727    ///
728    /// let mut v = AlignedVec::new();
729    /// v.extend_from_slice(&[1, 2, 3]);
730    ///
731    /// let vec = v.into_vec();
732    /// assert_eq!(vec.len(), 3);
733    /// assert_eq!(vec.as_slice(), &[1, 2, 3]);
734    /// ```
735    #[inline]
736    pub fn into_vec(self) -> Vec<u8> {
737        Vec::from(self.as_ref())
738    }
739}
740
741#[cfg(feature = "std")]
742const _: () = {
743    use std::io::{ErrorKind, Read};
744
745    impl AlignedVec {
746        /// Reads all bytes until EOF from `r` and appends them to this `AlignedVec`.
747        ///
748        /// If successful, this function will return the total number of bytes read.
749        ///
750        /// # Examples
751        /// ```
752        /// use rkyv::AlignedVec;
753        ///
754        /// let source = (0..4096).map(|x| (x % 256) as u8).collect::<Vec<_>>();
755        /// let mut bytes = AlignedVec::new();
756        /// bytes.extend_from_reader(&mut source.as_slice()).unwrap();
757        ///
758        /// assert_eq!(bytes.len(), 4096);
759        /// assert_eq!(bytes[0], 0);
760        /// assert_eq!(bytes[100], 100);
761        /// assert_eq!(bytes[2945], 129);
762        /// ```
763        pub fn extend_from_reader<R: Read + ?Sized>(
764            &mut self,
765            r: &mut R,
766        ) -> std::io::Result<usize> {
767            let start_len = self.len();
768            let start_cap = self.capacity();
769
770            // Extra initialized bytes from previous loop iteration.
771            let mut initialized = 0;
772            loop {
773                if self.len() == self.capacity() {
774                    // No available capacity, reserve some space.
775                    self.reserve(32);
776                }
777
778                let read_buf_start = unsafe { self.as_mut_ptr().add(self.len) };
779                let read_buf_len = self.capacity() - self.len();
780
781                // Initialize the uninitialized portion of the available space.
782                unsafe {
783                    // The first `initialized` bytes don't need to be zeroed.
784                    // This leaves us `read_buf_len - initialized` bytes to zero
785                    // starting at `initialized`.
786                    core::ptr::write_bytes(
787                        read_buf_start.add(initialized),
788                        0,
789                        read_buf_len - initialized,
790                    );
791                }
792
793                // The entire read buffer is now initialized, so we can create a
794                // mutable slice of it.
795                let read_buf =
796                    unsafe { core::slice::from_raw_parts_mut(read_buf_start, read_buf_len) };
797
798                match r.read(read_buf) {
799                    Ok(read) => {
800                        // We filled `read` additional bytes.
801                        unsafe {
802                            self.set_len(self.len() + read);
803                        }
804                        initialized = read_buf_len - read;
805
806                        if read == 0 {
807                            return Ok(self.len() - start_len);
808                        }
809                    }
810                    Err(e) if e.kind() == ErrorKind::Interrupted => continue,
811                    Err(e) => return Err(e),
812                }
813
814                if self.len() == self.capacity() && self.capacity() == start_cap {
815                    // The buffer might be an exact fit. Let's read into a probe buffer
816                    // and see if it returns `Ok(0)`. If so, we've avoided an
817                    // unnecessary doubling of the capacity. But if not, append the
818                    // probe buffer to the primary buffer and let its capacity grow.
819                    let mut probe = [0u8; 32];
820
821                    loop {
822                        match r.read(&mut probe) {
823                            Ok(0) => return Ok(self.len() - start_len),
824                            Ok(n) => {
825                                self.extend_from_slice(&probe[..n]);
826                                break;
827                            }
828                            Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
829                            Err(e) => return Err(e),
830                        }
831                    }
832                }
833            }
834        }
835    }
836};
837
838impl From<AlignedVec> for Vec<u8> {
839    #[inline]
840    fn from(aligned: AlignedVec) -> Self {
841        aligned.to_vec()
842    }
843}
844
845impl Archive for AlignedVec {
846    type Archived = ArchivedVec<u8>;
847    type Resolver = VecResolver;
848
849    #[inline]
850    unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
851        ArchivedVec::resolve_from_slice(self.as_slice(), pos, resolver, out);
852    }
853}
854
855impl AsMut<[u8]> for AlignedVec {
856    #[inline]
857    fn as_mut(&mut self) -> &mut [u8] {
858        self.as_mut_slice()
859    }
860}
861
862impl AsRef<[u8]> for AlignedVec {
863    #[inline]
864    fn as_ref(&self) -> &[u8] {
865        self.as_slice()
866    }
867}
868
869impl Borrow<[u8]> for AlignedVec {
870    #[inline]
871    fn borrow(&self) -> &[u8] {
872        self.as_slice()
873    }
874}
875
876impl BorrowMut<[u8]> for AlignedVec {
877    #[inline]
878    fn borrow_mut(&mut self) -> &mut [u8] {
879        self.as_mut_slice()
880    }
881}
882
883impl Clone for AlignedVec {
884    #[inline]
885    fn clone(&self) -> Self {
886        unsafe {
887            let mut result = AlignedVec::with_capacity(self.len);
888            result.len = self.len;
889            core::ptr::copy_nonoverlapping(self.as_ptr(), result.as_mut_ptr(), self.len);
890            result
891        }
892    }
893}
894
895impl fmt::Debug for AlignedVec {
896    #[inline]
897    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
898        self.as_slice().fmt(f)
899    }
900}
901
902impl Default for AlignedVec {
903    #[inline]
904    fn default() -> Self {
905        Self::new()
906    }
907}
908
909impl Deref for AlignedVec {
910    type Target = [u8];
911
912    #[inline]
913    fn deref(&self) -> &Self::Target {
914        self.as_slice()
915    }
916}
917
918impl DerefMut for AlignedVec {
919    #[inline]
920    fn deref_mut(&mut self) -> &mut Self::Target {
921        self.as_mut_slice()
922    }
923}
924
925impl<I: slice::SliceIndex<[u8]>> Index<I> for AlignedVec {
926    type Output = <I as slice::SliceIndex<[u8]>>::Output;
927
928    #[inline]
929    fn index(&self, index: I) -> &Self::Output {
930        &self.as_slice()[index]
931    }
932}
933
934impl<I: slice::SliceIndex<[u8]>> IndexMut<I> for AlignedVec {
935    #[inline]
936    fn index_mut(&mut self, index: I) -> &mut Self::Output {
937        &mut self.as_mut_slice()[index]
938    }
939}
940
941#[cfg(feature = "std")]
942impl io::Write for AlignedVec {
943    #[inline]
944    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
945        self.extend_from_slice(buf);
946        Ok(buf.len())
947    }
948
949    #[inline]
950    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
951        let len = bufs.iter().map(|b| b.len()).sum();
952        self.reserve(len);
953        for buf in bufs {
954            self.extend_from_slice(buf);
955        }
956        Ok(len)
957    }
958
959    #[inline]
960    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
961        self.extend_from_slice(buf);
962        Ok(())
963    }
964
965    fn flush(&mut self) -> io::Result<()> {
966        Ok(())
967    }
968}
969
970// SAFETY: AlignedVec is safe to send to another thread
971unsafe impl Send for AlignedVec {}
972
973impl<S: ScratchSpace + Serializer + ?Sized> Serialize<S> for AlignedVec {
974    #[inline]
975    fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
976        serializer.align(Self::ALIGNMENT)?;
977        ArchivedVec::<Archived<u8>>::serialize_from_slice(self.as_slice(), serializer)
978    }
979}
980
981// SAFETY: AlignedVec is safe to share between threads
982unsafe impl Sync for AlignedVec {}
983
984impl Unpin for AlignedVec {}