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