musli_core/alloc/vec.rs
1use core::borrow::Borrow;
2use core::cmp::Ordering;
3use core::fmt;
4use core::mem::ManuallyDrop;
5use core::ops::{Deref, DerefMut};
6use core::ptr;
7use core::slice;
8
9use crate::de::{DecodeBytes, UnsizedVisitor};
10use crate::{Context, Decoder};
11
12#[cfg(feature = "alloc")]
13use super::Global;
14use super::{Alloc, AllocError, Allocator, Disabled};
15
16/// A Müsli-allocated contiguous growable array type, written as `Vec<T>`, short
17/// for 'vector'.
18///
19/// `String` is the most common string type. It has ownership over the contents
20/// of the string, stored in a heap-allocated buffer (see
21/// [Representation](#representation)). It is closely related to its borrowed
22/// counterpart, the primitive [`str`].
23///
24/// This is a [`Vec`][std-vec] type capable of using the allocator provided
25/// through a [`Context`]. Therefore it can be safely used in no-std
26/// environments.
27///
28/// [std-vec]: std::vec::Vec
29/// [`str`]: prim@str
30pub struct Vec<T, A>
31where
32 A: Allocator,
33{
34 buf: A::Alloc<T>,
35 len: usize,
36}
37
38const _: () = {
39 const fn assert_send_sync<T: Send + Sync>() {}
40 assert_send_sync::<Vec<u8, Disabled>>();
41};
42
43impl<T, A> Vec<T, A>
44where
45 A: Allocator,
46{
47 /// Construct a new buffer vector.
48 ///
49 /// ## Examples
50 ///
51 /// ```
52 /// use musli::alloc::{AllocError, Vec};
53 ///
54 /// musli::alloc::default(|alloc| {
55 /// let mut a = Vec::new_in(alloc);
56 ///
57 /// a.push(String::from("Hello"))?;
58 /// a.push(String::from("World"))?;
59 ///
60 /// assert_eq!(a.as_slice(), ["Hello", "World"]);
61 /// Ok::<_, AllocError>(())
62 /// });
63 /// # Ok::<_, AllocError>(())
64 /// ```
65 #[inline]
66 pub fn new_in(alloc: A) -> Self {
67 Self {
68 buf: alloc.alloc_empty::<T>(),
69 len: 0,
70 }
71 }
72
73 /// Coerce into a std vector.
74 #[cfg(feature = "alloc")]
75 pub fn into_std(self) -> Result<rust_alloc::vec::Vec<T>, Self> {
76 if !A::IS_GLOBAL {
77 return Err(self);
78 }
79
80 let mut this = ManuallyDrop::new(self);
81
82 // SAFETY: The implementation requirements of `Allocator` requires that
83 // this is possible.
84 unsafe {
85 let ptr = this.buf.as_mut_ptr();
86 let cap = this.buf.capacity();
87
88 Ok(rust_alloc::vec::Vec::from_raw_parts(ptr, this.len, cap))
89 }
90 }
91
92 /// Construct a new buffer vector.
93 ///
94 /// ## Examples
95 ///
96 /// ```
97 /// use musli::alloc::{AllocError, Vec};
98 ///
99 /// musli::alloc::default(|alloc| {
100 /// let mut a = Vec::with_capacity_in(2, alloc)?;
101 ///
102 /// a.push(String::from("Hello"))?;
103 /// a.push(String::from("World"))?;
104 ///
105 /// assert_eq!(a.as_slice(), ["Hello", "World"]);
106 /// Ok::<_, AllocError>(())
107 /// });
108 /// # Ok::<_, AllocError>(())
109 /// ```
110 #[inline]
111 pub fn with_capacity_in(capacity: usize, alloc: A) -> Result<Self, AllocError> {
112 let mut buf = alloc.alloc_empty::<T>();
113 buf.resize(0, capacity)?;
114 Ok(Self { buf, len: 0 })
115 }
116
117 /// Returns the number of elements in the vector, also referred to as its
118 /// 'length'.
119 ///
120 /// ## Examples
121 ///
122 /// ```
123 /// use musli::alloc::{AllocError, Vec};
124 ///
125 /// musli::alloc::default(|alloc| {
126 /// let mut a = Vec::new_in(alloc);
127 ///
128 /// assert_eq!(a.len(), 0);
129 /// a.extend_from_slice(b"Hello")?;
130 /// assert_eq!(a.len(), 5);
131 /// Ok::<_, AllocError>(())
132 /// })?;
133 /// # Ok::<_, musli::alloc::AllocError>(())
134 /// ```
135 #[inline]
136 pub fn len(&self) -> usize {
137 self.len
138 }
139
140 /// Returns the total number of elements the vector can hold without
141 /// reallocating.
142 ///
143 /// ## Examples
144 ///
145 /// ```
146 /// use musli::alloc::{AllocError, Vec};
147 ///
148 /// musli::alloc::default(|alloc| {
149 /// let mut a = Vec::new_in(alloc);
150 ///
151 /// assert_eq!(a.len(), 0);
152 /// assert_eq!(a.capacity(), 0);
153 ///
154 /// a.extend_from_slice(b"Hello")?;
155 /// assert_eq!(a.len(), 5);
156 /// assert!(a.capacity() >= 5);
157 ///
158 /// Ok::<_, AllocError>(())
159 /// })?;
160 /// # Ok::<_, musli::alloc::AllocError>(())
161 /// ```
162 #[inline]
163 pub fn capacity(&self) -> usize {
164 self.buf.capacity()
165 }
166
167 /// Reserves capacity for at least `additional` more elements to be inserted
168 /// in the given `Vec<T>`. The collection may reserve more space to
169 /// speculatively avoid frequent reallocations. After calling `reserve`,
170 /// capacity will be greater than or equal to `self.len() + additional`.
171 /// Does nothing if capacity is already sufficient.
172 ///
173 /// # Panics
174 ///
175 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use musli::alloc::{AllocError, Vec};
181 ///
182 /// musli::alloc::default(|alloc| {
183 /// let mut vec = Vec::new_in(alloc);
184 /// vec.push(1)?;
185 /// vec.reserve(10)?;
186 /// assert!(vec.capacity() >= 11);
187 /// Ok::<_, AllocError>(())
188 /// })?;
189 /// # Ok::<_, musli::alloc::AllocError>(())
190 /// ```
191 pub fn reserve(&mut self, additional: usize) -> Result<(), AllocError> {
192 if size_of::<T>() != 0 {
193 self.buf.resize(self.len, additional)?;
194 }
195
196 Ok(())
197 }
198
199 /// Check if the buffer is empty.
200 ///
201 /// ## Examples
202 ///
203 /// ```
204 /// use musli::alloc::{AllocError, Vec};
205 ///
206 /// musli::alloc::default(|alloc| {
207 /// let mut a = Vec::new_in(alloc);
208 ///
209 /// assert!(a.is_empty());
210 /// a.extend_from_slice(b"Hello")?;
211 /// assert!(!a.is_empty());
212 /// Ok::<_, AllocError>(())
213 /// });
214 /// # Ok::<_, AllocError>(())
215 /// ```
216 #[inline]
217 pub fn is_empty(&self) -> bool {
218 self.len == 0
219 }
220
221 /// Write a single item.
222 ///
223 /// Returns `true` if the item could be successfully written. A `false`
224 /// value indicates that we are out of buffer capacity.
225 ///
226 /// ## Examples
227 ///
228 /// ```
229 /// use musli::alloc::Vec;
230 ///
231 /// musli::alloc::default(|alloc| {
232 /// let mut a = Vec::new_in(alloc);
233 ///
234 /// a.push(b'H');
235 /// a.push(b'e');
236 /// a.push(b'l');
237 /// a.push(b'l');
238 /// a.push(b'o');
239 ///
240 /// assert_eq!(a.as_slice(), b"Hello");
241 /// });
242 /// ```
243 #[inline]
244 pub fn push(&mut self, item: T) -> Result<(), AllocError> {
245 if size_of::<T>() != 0 {
246 self.buf.resize(self.len, 1)?;
247
248 // SAFETY: The call to reserve ensures that we have enough capacity.
249 unsafe {
250 self.buf.as_mut_ptr().add(self.len).write(item);
251 }
252 }
253
254 self.len += 1;
255 Ok(())
256 }
257
258 /// Pop a single item from the buffer.
259 ///
260 /// Returns `None` if the buffer is empty.
261 ///
262 /// ## Examples
263 ///
264 /// ```
265 /// use musli::alloc::Vec;
266 ///
267 /// musli::alloc::default(|alloc| {
268 /// let mut a = Vec::new_in(alloc);
269 ///
270 /// a.push(String::from("foo"));
271 /// a.push(String::from("bar"));
272 ///
273 /// assert_eq!(a.as_slice(), ["foo", "bar"]);
274 ///
275 /// assert_eq!(a.pop().as_deref(), Some("bar"));
276 /// assert_eq!(a.pop().as_deref(), Some("foo"));
277 /// assert_eq!(a.pop(), None);
278 /// });
279 /// ```
280 #[inline]
281 pub fn pop(&mut self) -> Option<T> {
282 if self.len == 0 {
283 return None;
284 }
285
286 self.len -= 1;
287 // SAFETY: We know that the buffer is initialized up to `len`.
288 unsafe { Some(ptr::read(self.buf.as_ptr().add(self.len))) }
289 }
290
291 /// Clear the buffer vector.
292 ///
293 /// ## Examples
294 ///
295 /// ```
296 /// use musli::alloc::Vec;
297 ///
298 /// musli::alloc::default(|alloc| {
299 /// let mut a = Vec::new_in(alloc);
300 ///
301 /// a.push(b'H');
302 /// a.push(b'e');
303 /// a.push(b'l');
304 /// a.push(b'l');
305 /// a.push(b'o');
306 ///
307 /// assert_eq!(a.as_slice(), b"Hello");
308 /// a.clear();
309 /// assert_eq!(a.as_slice(), b"");
310 /// });
311 /// ```
312 #[inline]
313 pub fn clear(&mut self) {
314 // SAFETY: We know that the buffer is initialized up to `len`.
315 unsafe { ptr::drop_in_place(slice::from_raw_parts_mut(self.buf.as_mut_ptr(), self.len)) }
316 self.len = 0;
317 }
318
319 /// Get the initialized part of the buffer as a slice.
320 ///
321 /// ## Examples
322 ///
323 /// ```
324 /// use musli::alloc::{AllocError, Vec};
325 ///
326 /// musli::alloc::default(|alloc| {
327 /// let mut a = Vec::new_in(alloc);
328 /// assert_eq!(a.as_slice(), b"");
329 /// a.extend_from_slice(b"Hello")?;
330 /// assert_eq!(a.as_slice(), b"Hello");
331 /// Ok::<_, AllocError>(())
332 /// });
333 /// # Ok::<_, musli::alloc::AllocError>(())
334 /// ```
335 #[inline]
336 pub fn as_slice(&self) -> &[T] {
337 // SAFETY: We know that the buffer is initialized up to `self.len`.
338 unsafe { slice::from_raw_parts(self.buf.as_ptr(), self.len) }
339 }
340
341 /// Get the initialized part of the buffer as a slice.
342 ///
343 /// ## Examples
344 ///
345 /// ```
346 /// use musli::alloc::{AllocError, Vec};
347 ///
348 /// musli::alloc::default(|alloc| {
349 /// let mut a = Vec::new_in(alloc);
350 /// assert_eq!(a.as_slice(), b"");
351 /// a.extend_from_slice(b"Hello")?;
352 /// assert_eq!(a.as_slice(), b"Hello");
353 /// a.as_mut_slice().make_ascii_uppercase();
354 /// assert_eq!(a.as_slice(), b"HELLO");
355 /// Ok::<_, AllocError>(())
356 /// });
357 /// # Ok::<_, musli::alloc::AllocError>(())
358 /// ```
359 #[inline]
360 pub fn as_mut_slice(&mut self) -> &mut [T] {
361 // SAFETY: We know that the buffer is initialized up to `self.len`.
362 unsafe { slice::from_raw_parts_mut(self.buf.as_mut_ptr(), self.len) }
363 }
364
365 /// Deconstruct a vector into its raw parts.
366 ///
367 /// ## Examples
368 ///
369 /// ```
370 /// use musli::alloc::{Allocator, AllocError, Vec};
371 ///
372 /// fn operate<A>(alloc: A) -> Result<(), AllocError>
373 /// where
374 /// A: Allocator
375 /// {
376 /// let mut a = Vec::new_in(alloc);
377 /// a.extend_from_slice(b"abc")?;
378 /// let (buf, len) = a.into_raw_parts();
379 ///
380 /// let b = Vec::<_, A>::from_raw_parts(buf, len);
381 /// assert_eq!(b.as_slice(), b"abc");
382 /// Ok::<_, AllocError>(())
383 /// }
384 ///
385 /// musli::alloc::default(|alloc| operate(alloc))?;
386 /// # Ok::<_, musli::alloc::AllocError>(())
387 /// ```
388 #[inline]
389 pub fn into_raw_parts(self) -> (A::Alloc<T>, usize) {
390 let this = ManuallyDrop::new(self);
391
392 // SAFETY: The interior buffer is valid and will not be dropped thanks to `ManuallyDrop`.
393 unsafe {
394 let buf = ptr::addr_of!(this.buf).read();
395 (buf, this.len)
396 }
397 }
398
399 /// Construct a vector from raw parts.
400 ///
401 /// ## Examples
402 ///
403 /// ```
404 /// use musli::alloc::{Allocator, AllocError, Vec};
405 ///
406 /// fn operate<A>(alloc: A) -> Result<(), AllocError>
407 /// where
408 /// A: Allocator
409 /// {
410 /// let mut a = Vec::new_in(alloc);
411 /// a.extend_from_slice(b"abc")?;
412 /// let (buf, len) = a.into_raw_parts();
413 ///
414 /// let b = Vec::<_, A>::from_raw_parts(buf, len);
415 /// assert_eq!(b.as_slice(), b"abc");
416 /// Ok::<_, AllocError>(())
417 /// }
418 ///
419 /// musli::alloc::default(|alloc| operate(alloc))?;
420 /// # Ok::<_, musli::alloc::AllocError>(())
421 /// ```
422 #[inline]
423 pub fn from_raw_parts(buf: A::Alloc<T>, len: usize) -> Self {
424 Self { buf, len }
425 }
426
427 /// Forces the length of the vector to `new_len`.
428 ///
429 /// This is a low-level operation that maintains none of the normal
430 /// invariants of the type. Normally changing the length of a vector is done
431 /// using one of the safe operations instead, such as [`extend`], or
432 /// [`clear`].
433 ///
434 /// [`extend`]: Extend::extend
435 /// [`clear`]: Vec::clear
436 ///
437 /// # Safety
438 ///
439 /// - `new_len` must be less than or equal to [`capacity()`].
440 /// - The elements at `old_len..new_len` must be initialized.
441 ///
442 /// [`capacity()`]: Vec::capacity
443 #[inline]
444 pub unsafe fn set_len(&mut self, new_len: usize) {
445 debug_assert!(new_len <= self.capacity());
446 self.len = new_len;
447 }
448
449 /// Access a reference to the raw underlying allocation.
450 pub const fn raw(&self) -> &A::Alloc<T> {
451 &self.buf
452 }
453}
454
455impl<T, A> Vec<T, A>
456where
457 A: Allocator,
458 T: Copy,
459{
460 /// Write the given number of bytes.
461 ///
462 /// Returns `true` if the bytes could be successfully written. A `false`
463 /// value indicates that we are out of buffer capacity.
464 ///
465 /// ## Examples
466 ///
467 /// ```
468 /// use musli::alloc::Vec;
469 ///
470 /// musli::alloc::default(|alloc| {
471 /// let mut a = Vec::new_in(alloc);
472 /// assert_eq!(a.len(), 0);
473 /// a.extend_from_slice(b"Hello");
474 /// assert_eq!(a.len(), 5);
475 /// });
476 /// ```
477 #[inline]
478 pub fn extend_from_slice(&mut self, items: &[T]) -> Result<(), AllocError> {
479 if size_of::<T>() != 0 {
480 self.buf.resize(self.len, items.len())?;
481
482 // SAFETY: The call to reserve ensures that we have enough capacity.
483 unsafe {
484 self.buf
485 .as_mut_ptr()
486 .add(self.len)
487 .copy_from_nonoverlapping(items.as_ptr(), items.len());
488 }
489 }
490
491 self.len += items.len();
492 Ok(())
493 }
494
495 /// Write a buffer of the same type onto the current buffer.
496 ///
497 /// This allows allocators to provide more efficient means of extending the
498 /// current buffer with one provided from the same allocator.
499 ///
500 /// ## Examples
501 ///
502 /// ```
503 /// use musli::alloc::{AllocError, Vec};
504 ///
505 /// musli::alloc::default(|alloc| {
506 /// let mut a = Vec::new_in(alloc);
507 /// let mut b = Vec::new_in(alloc);
508 ///
509 /// a.extend_from_slice(b"Hello")?;
510 /// b.extend_from_slice(b" World")?;
511 ///
512 /// a.extend(b)?;
513 /// assert_eq!(a.as_slice(), b"Hello World");
514 /// Ok::<_, AllocError>(())
515 /// });
516 /// # Ok::<_, AllocError>(())
517 /// ```
518 #[inline]
519 pub fn extend(&mut self, other: Vec<T, A>) -> Result<(), AllocError> {
520 let (other, other_len) = other.into_raw_parts();
521
522 // Try to merge one buffer with another.
523 if let Err(buf) = self.buf.try_merge(self.len, other, other_len) {
524 let other = Vec::<T, A>::from_raw_parts(buf, other_len);
525 return self.extend_from_slice(other.as_slice());
526 }
527
528 self.len += other_len;
529 Ok(())
530 }
531}
532
533/// Try to write a format string into the buffer.
534///
535/// ## Examples
536///
537/// ```
538/// use core::fmt::Write;
539///
540/// use musli::alloc::Vec;
541///
542/// musli::alloc::default(|alloc| {
543/// let mut a = Vec::new_in(alloc);
544/// let world = "World";
545///
546/// write!(a, "Hello {world}")?;
547///
548/// assert_eq!(a.as_slice(), b"Hello World");
549/// Ok(())
550/// })?;
551/// # Ok::<_, core::fmt::Error>(())
552/// ```
553impl<A> fmt::Write for Vec<u8, A>
554where
555 A: Allocator,
556{
557 #[inline]
558 fn write_str(&mut self, s: &str) -> fmt::Result {
559 self.extend_from_slice(s.as_bytes()).map_err(|_| fmt::Error)
560 }
561}
562
563impl<T, A> Deref for Vec<T, A>
564where
565 A: Allocator,
566{
567 type Target = [T];
568
569 #[inline]
570 fn deref(&self) -> &Self::Target {
571 self.as_slice()
572 }
573}
574
575impl<T, A> DerefMut for Vec<T, A>
576where
577 A: Allocator,
578{
579 #[inline]
580 fn deref_mut(&mut self) -> &mut Self::Target {
581 self.as_mut_slice()
582 }
583}
584
585impl<T, A> fmt::Debug for Vec<T, A>
586where
587 T: fmt::Debug,
588 A: Allocator,
589{
590 #[inline]
591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592 f.debug_list().entries(self.as_slice()).finish()
593 }
594}
595
596impl<T, A> Drop for Vec<T, A>
597where
598 A: Allocator,
599{
600 fn drop(&mut self) {
601 self.clear();
602 }
603}
604
605impl<T, A> AsRef<[T]> for Vec<T, A>
606where
607 A: Allocator,
608{
609 #[inline]
610 fn as_ref(&self) -> &[T] {
611 self
612 }
613}
614
615impl<T, A> AsMut<[T]> for Vec<T, A>
616where
617 A: Allocator,
618{
619 #[inline]
620 fn as_mut(&mut self) -> &mut [T] {
621 self
622 }
623}
624
625macro_rules! impl_eq {
626 ($lhs:ty, $rhs: ty) => {
627 #[allow(unused_lifetimes)]
628 impl<'a, 'b, T, A> PartialEq<$rhs> for $lhs
629 where
630 T: PartialEq,
631 A: Allocator,
632 {
633 #[inline]
634 fn eq(&self, other: &$rhs) -> bool {
635 PartialEq::eq(&self[..], &other[..])
636 }
637
638 #[inline]
639 #[allow(clippy::partialeq_ne_impl)]
640 fn ne(&self, other: &$rhs) -> bool {
641 PartialEq::ne(&self[..], &other[..])
642 }
643 }
644
645 #[allow(unused_lifetimes)]
646 impl<'a, 'b, T, A> PartialEq<$lhs> for $rhs
647 where
648 T: PartialEq,
649 A: Allocator,
650 {
651 #[inline]
652 fn eq(&self, other: &$lhs) -> bool {
653 PartialEq::eq(&self[..], &other[..])
654 }
655
656 #[inline]
657 #[allow(clippy::partialeq_ne_impl)]
658 fn ne(&self, other: &$lhs) -> bool {
659 PartialEq::ne(&self[..], &other[..])
660 }
661 }
662 };
663}
664
665macro_rules! impl_eq_array {
666 ($lhs:ty, $rhs: ty) => {
667 #[allow(unused_lifetimes)]
668 impl<'a, 'b, T, A, const N: usize> PartialEq<$rhs> for $lhs
669 where
670 T: PartialEq,
671 A: Allocator,
672 {
673 #[inline]
674 fn eq(&self, other: &$rhs) -> bool {
675 PartialEq::eq(&self[..], &other[..])
676 }
677
678 #[inline]
679 #[allow(clippy::partialeq_ne_impl)]
680 fn ne(&self, other: &$rhs) -> bool {
681 PartialEq::ne(&self[..], &other[..])
682 }
683 }
684
685 #[allow(unused_lifetimes)]
686 impl<'a, 'b, T, A, const N: usize> PartialEq<$lhs> for $rhs
687 where
688 T: PartialEq,
689 A: Allocator,
690 {
691 #[inline]
692 fn eq(&self, other: &$lhs) -> bool {
693 PartialEq::eq(&self[..], &other[..])
694 }
695
696 #[inline]
697 #[allow(clippy::partialeq_ne_impl)]
698 fn ne(&self, other: &$lhs) -> bool {
699 PartialEq::ne(&self[..], &other[..])
700 }
701 }
702 };
703}
704
705impl_eq! { Vec<T, A>, [T] }
706impl_eq! { Vec<T, A>, &'a [T] }
707impl_eq_array! { Vec<T, A>, [T; N] }
708impl_eq_array! { Vec<T, A>, &'a [T; N] }
709
710impl<T, A, B> PartialEq<Vec<T, B>> for Vec<T, A>
711where
712 T: PartialEq,
713 A: Allocator,
714 B: Allocator,
715{
716 #[inline]
717 fn eq(&self, other: &Vec<T, B>) -> bool {
718 self.as_slice().eq(other.as_slice())
719 }
720}
721
722impl<T, A> Eq for Vec<T, A>
723where
724 T: Eq,
725 A: Allocator,
726{
727}
728
729impl<T, A, B> PartialOrd<Vec<T, B>> for Vec<T, A>
730where
731 T: PartialOrd,
732 A: Allocator,
733 B: Allocator,
734{
735 #[inline]
736 fn partial_cmp(&self, other: &Vec<T, B>) -> Option<Ordering> {
737 self.as_slice().partial_cmp(other.as_slice())
738 }
739}
740
741impl<T, A> Ord for Vec<T, A>
742where
743 T: Ord,
744 A: Allocator,
745{
746 #[inline]
747 fn cmp(&self, other: &Self) -> Ordering {
748 self.as_slice().cmp(other.as_slice())
749 }
750}
751
752impl<T, A> Borrow<[T]> for Vec<T, A>
753where
754 A: Allocator,
755{
756 #[inline]
757 fn borrow(&self) -> &[T] {
758 self
759 }
760}
761
762/// Conversion from a std [`Vec`][std-vec] to a Müsli-allocated [`Vec`] in the
763/// [`Global`] allocator.
764///
765/// [std-vec]: rust_alloc::vec::Vec
766///
767/// # Examples
768///
769/// ```
770/// use musli::alloc::Vec;
771///
772/// let values = vec![1, 2, 3, 4];
773/// let values2 = Vec::from(values);
774/// ```
775#[cfg(feature = "alloc")]
776#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
777impl<T> From<rust_alloc::vec::Vec<T>> for Vec<T, Global> {
778 #[inline]
779 fn from(value: rust_alloc::vec::Vec<T>) -> Self {
780 use core::ptr::NonNull;
781
782 // SAFETY: We know that the vector was allocated as expected using the
783 // global allocator.
784 unsafe {
785 let mut value = ManuallyDrop::new(value);
786 let ptr = NonNull::new_unchecked(value.as_mut_ptr());
787 let len = value.len();
788 let cap = value.capacity();
789
790 let buf = Global::slice_from_raw_parts(ptr, cap);
791 Vec::from_raw_parts(buf, len)
792 }
793 }
794}
795
796/// Decode implementation for a Müsli-allocated byte array stored in a [`Vec`].
797///
798/// # Examples
799///
800/// ```
801/// use musli::alloc::Vec;
802/// use musli::{Allocator, Decode};
803///
804/// #[derive(Decode)]
805/// struct Struct<A> where A: Allocator {
806/// #[musli(bytes)]
807/// field: Vec<u8, A>
808/// }
809/// ```
810impl<'de, M, A> DecodeBytes<'de, M, A> for Vec<u8, A>
811where
812 A: Allocator,
813{
814 const DECODE_BYTES_PACKED: bool = false;
815
816 #[inline]
817 fn decode_bytes<D>(decoder: D) -> Result<Self, D::Error>
818 where
819 D: Decoder<'de, Mode = M, Allocator = A>,
820 {
821 struct Visitor;
822
823 #[crate::de::unsized_visitor(crate)]
824 impl<C> UnsizedVisitor<'_, C, [u8]> for Visitor
825 where
826 C: Context,
827 {
828 type Ok = Vec<u8, Self::Allocator>;
829
830 #[inline]
831 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832 write!(f, "bytes")
833 }
834
835 #[inline]
836 fn visit_owned(
837 self,
838 _: C,
839 value: Vec<u8, Self::Allocator>,
840 ) -> Result<Self::Ok, Self::Error> {
841 Ok(value)
842 }
843
844 #[inline]
845 fn visit_ref(self, cx: C, bytes: &[u8]) -> Result<Self::Ok, Self::Error> {
846 let mut buf = Vec::new_in(cx.alloc());
847 buf.extend_from_slice(bytes).map_err(cx.map())?;
848 Ok(buf)
849 }
850 }
851
852 decoder.decode_bytes(Visitor)
853 }
854}
855
856crate::internal::macros::slice_sequence! {
857 cx,
858 Vec<T, A>,
859 || Vec::new_in(cx.alloc()),
860 |vec, value| vec.push(value).map_err(cx.map())?,
861 |vec, capacity| vec.reserve(capacity).map_err(cx.map())?,
862 |capacity| Vec::with_capacity_in(capacity, cx.alloc()).map_err(cx.map())?,
863}