Skip to main content

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        //
303        // Set to zero in case dropping panics so we can't incidentally access
304        // uninitialized data in case the panic is caught.
305        unsafe {
306            let data = ptr::slice_from_raw_parts_mut(self.buf.as_mut_ptr(), self.len);
307
308            self.len = 0;
309            ptr::drop_in_place(data);
310        }
311    }
312
313    /// Get the initialized part of the buffer as a slice.
314    ///
315    /// ## Examples
316    ///
317    /// ```
318    /// use musli::alloc::{AllocError, Vec};
319    ///
320    /// musli::alloc::default(|alloc| {
321    ///     let mut a = Vec::new_in(alloc);
322    ///     assert_eq!(a.as_slice(), b"");
323    ///     a.extend_from_slice(b"Hello")?;
324    ///     assert_eq!(a.as_slice(), b"Hello");
325    ///     Ok::<_, AllocError>(())
326    /// });
327    /// # Ok::<_, musli::alloc::AllocError>(())
328    /// ```
329    #[inline]
330    pub fn as_slice(&self) -> &[T] {
331        // SAFETY: We know that the buffer is initialized up to `self.len`.
332        unsafe { slice::from_raw_parts(self.buf.as_ptr(), self.len) }
333    }
334
335    /// Get the initialized part of the buffer as a slice.
336    ///
337    /// ## Examples
338    ///
339    /// ```
340    /// use musli::alloc::{AllocError, Vec};
341    ///
342    /// musli::alloc::default(|alloc| {
343    ///     let mut a = Vec::new_in(alloc);
344    ///     assert_eq!(a.as_slice(), b"");
345    ///     a.extend_from_slice(b"Hello")?;
346    ///     assert_eq!(a.as_slice(), b"Hello");
347    ///     a.as_mut_slice().make_ascii_uppercase();
348    ///     assert_eq!(a.as_slice(), b"HELLO");
349    ///     Ok::<_, AllocError>(())
350    /// });
351    /// # Ok::<_, musli::alloc::AllocError>(())
352    /// ```
353    #[inline]
354    pub fn as_mut_slice(&mut self) -> &mut [T] {
355        // SAFETY: We know that the buffer is initialized up to `self.len`.
356        unsafe { slice::from_raw_parts_mut(self.buf.as_mut_ptr(), self.len) }
357    }
358
359    /// Deconstruct a vector into its raw parts.
360    ///
361    /// ## Examples
362    ///
363    /// ```
364    /// use musli::alloc::{Allocator, AllocError, Vec};
365    ///
366    /// fn operate<A>(alloc: A) -> Result<(), AllocError>
367    /// where
368    ///     A: Allocator
369    /// {
370    ///     let mut a = Vec::new_in(alloc);
371    ///     a.extend_from_slice(b"abc")?;
372    ///     let (buf, len) = a.into_raw_parts();
373    ///
374    ///     let b = Vec::<_, A>::from_raw_parts(buf, len);
375    ///     assert_eq!(b.as_slice(), b"abc");
376    ///     Ok::<_, AllocError>(())
377    /// }
378    ///
379    /// musli::alloc::default(|alloc| operate(alloc))?;
380    /// # Ok::<_, musli::alloc::AllocError>(())
381    /// ```
382    #[inline]
383    pub fn into_raw_parts(self) -> (A::Alloc<T>, usize) {
384        let this = ManuallyDrop::new(self);
385
386        // SAFETY: The interior buffer is valid and will not be dropped thanks to `ManuallyDrop`.
387        unsafe {
388            let buf = ptr::addr_of!(this.buf).read();
389            (buf, this.len)
390        }
391    }
392
393    /// Construct a vector from raw parts.
394    ///
395    /// ## Examples
396    ///
397    /// ```
398    /// use musli::alloc::{Allocator, AllocError, Vec};
399    ///
400    /// fn operate<A>(alloc: A) -> Result<(), AllocError>
401    /// where
402    ///     A: Allocator
403    /// {
404    ///     let mut a = Vec::new_in(alloc);
405    ///     a.extend_from_slice(b"abc")?;
406    ///     let (buf, len) = a.into_raw_parts();
407    ///
408    ///     let b = Vec::<_, A>::from_raw_parts(buf, len);
409    ///     assert_eq!(b.as_slice(), b"abc");
410    ///     Ok::<_, AllocError>(())
411    /// }
412    ///
413    /// musli::alloc::default(|alloc| operate(alloc))?;
414    /// # Ok::<_, musli::alloc::AllocError>(())
415    /// ```
416    #[inline]
417    pub fn from_raw_parts(buf: A::Alloc<T>, len: usize) -> Self {
418        Self { buf, len }
419    }
420
421    /// Forces the length of the vector to `new_len`.
422    ///
423    /// This is a low-level operation that maintains none of the normal
424    /// invariants of the type. Normally changing the length of a vector is done
425    /// using one of the safe operations instead, such as [`extend`], or
426    /// [`clear`].
427    ///
428    /// [`extend`]: Extend::extend
429    /// [`clear`]: Vec::clear
430    ///
431    /// # Safety
432    ///
433    /// - `new_len` must be less than or equal to [`capacity()`].
434    /// - The elements at `old_len..new_len` must be initialized.
435    ///
436    /// [`capacity()`]: Vec::capacity
437    #[inline]
438    pub unsafe fn set_len(&mut self, new_len: usize) {
439        debug_assert!(new_len <= self.capacity());
440        self.len = new_len;
441    }
442
443    /// Access a reference to the raw underlying allocation.
444    pub const fn raw(&self) -> &A::Alloc<T> {
445        &self.buf
446    }
447}
448
449impl<T, A> Clone for Vec<T, A>
450where
451    T: Clone,
452    A: GlobalAllocator,
453{
454    #[inline]
455    fn clone(&self) -> Self {
456        let mut this = Self {
457            buf: <A as GlobalAllocator>::clone_alloc(&self.buf),
458            len: 0,
459        };
460
461        let mut b = this.buf.as_mut_ptr();
462
463        for item in self.as_slice() {
464            // SAFETY: We know that the buffer is initialized up to `self.len`.
465            unsafe {
466                b.write(item.clone());
467                b = b.add(1);
468                // If cloning fails we don't want to drop interior items, so we
469                // keep track of length *after* cloning.
470                this.len += 1;
471            }
472        }
473
474        this
475    }
476}
477
478impl<T, A> Vec<T, A>
479where
480    A: Allocator,
481    T: Copy,
482{
483    /// Write the given number of bytes.
484    ///
485    /// Returns `true` if the bytes could be successfully written. A `false`
486    /// value indicates that we are out of buffer capacity.
487    ///
488    /// ## Examples
489    ///
490    /// ```
491    /// use musli::alloc::Vec;
492    ///
493    /// musli::alloc::default(|alloc| {
494    ///     let mut a = Vec::new_in(alloc);
495    ///     assert_eq!(a.len(), 0);
496    ///     a.extend_from_slice(b"Hello");
497    ///     assert_eq!(a.len(), 5);
498    /// });
499    /// ```
500    #[inline]
501    pub fn extend_from_slice(&mut self, items: &[T]) -> Result<(), AllocError> {
502        if size_of::<T>() != 0 {
503            self.buf.resize(self.len, items.len())?;
504
505            // SAFETY: The call to reserve ensures that we have enough capacity.
506            unsafe {
507                self.buf
508                    .as_mut_ptr()
509                    .add(self.len)
510                    .copy_from_nonoverlapping(items.as_ptr(), items.len());
511            }
512        }
513
514        self.len += items.len();
515        Ok(())
516    }
517
518    /// Write a buffer of the same type onto the current buffer.
519    ///
520    /// This allows allocators to provide more efficient means of extending the
521    /// current buffer with one provided from the same allocator.
522    ///
523    /// ## Examples
524    ///
525    /// ```
526    /// use musli::alloc::{AllocError, Vec};
527    ///
528    /// musli::alloc::default(|alloc| {
529    ///     let mut a = Vec::new_in(alloc);
530    ///     let mut b = Vec::new_in(alloc);
531    ///
532    ///     a.extend_from_slice(b"Hello")?;
533    ///     b.extend_from_slice(b" World")?;
534    ///
535    ///     a.extend(b)?;
536    ///     assert_eq!(a.as_slice(), b"Hello World");
537    ///     Ok::<_, AllocError>(())
538    /// });
539    /// # Ok::<_, AllocError>(())
540    /// ```
541    #[inline]
542    pub fn extend(&mut self, other: Vec<T, A>) -> Result<(), AllocError> {
543        let (other, other_len) = other.into_raw_parts();
544
545        // Try to merge one buffer with another.
546        if let Err(buf) = self.buf.try_merge(self.len, other, other_len) {
547            let other = Vec::<T, A>::from_raw_parts(buf, other_len);
548            return self.extend_from_slice(other.as_slice());
549        }
550
551        self.len += other_len;
552        Ok(())
553    }
554}
555
556/// Try to write a format string into the buffer.
557///
558/// ## Examples
559///
560/// ```
561/// use core::fmt::Write;
562///
563/// use musli::alloc::Vec;
564///
565/// musli::alloc::default(|alloc| {
566///     let mut a = Vec::new_in(alloc);
567///     let world = "World";
568///
569///     write!(a, "Hello {world}")?;
570///
571///     assert_eq!(a.as_slice(), b"Hello World");
572///     Ok(())
573/// })?;
574/// # Ok::<_, core::fmt::Error>(())
575/// ```
576impl<A> fmt::Write for Vec<u8, A>
577where
578    A: Allocator,
579{
580    #[inline]
581    fn write_str(&mut self, s: &str) -> fmt::Result {
582        self.extend_from_slice(s.as_bytes()).map_err(|_| fmt::Error)
583    }
584}
585
586impl<T, A> Deref for Vec<T, A>
587where
588    A: Allocator,
589{
590    type Target = [T];
591
592    #[inline]
593    fn deref(&self) -> &Self::Target {
594        self.as_slice()
595    }
596}
597
598impl<T, A> DerefMut for Vec<T, A>
599where
600    A: Allocator,
601{
602    #[inline]
603    fn deref_mut(&mut self) -> &mut Self::Target {
604        self.as_mut_slice()
605    }
606}
607
608impl<T, A> fmt::Debug for Vec<T, A>
609where
610    T: fmt::Debug,
611    A: Allocator,
612{
613    #[inline]
614    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615        f.debug_list().entries(self.as_slice()).finish()
616    }
617}
618
619impl<T, A> Drop for Vec<T, A>
620where
621    A: Allocator,
622{
623    fn drop(&mut self) {
624        self.clear();
625    }
626}
627
628impl<T, A> AsRef<[T]> for Vec<T, A>
629where
630    A: Allocator,
631{
632    #[inline]
633    fn as_ref(&self) -> &[T] {
634        self
635    }
636}
637
638impl<T, A> AsMut<[T]> for Vec<T, A>
639where
640    A: Allocator,
641{
642    #[inline]
643    fn as_mut(&mut self) -> &mut [T] {
644        self
645    }
646}
647
648macro_rules! impl_eq {
649    ($lhs:ty, $rhs: ty) => {
650        #[allow(unused_lifetimes)]
651        impl<'a, 'b, T, A> PartialEq<$rhs> for $lhs
652        where
653            T: PartialEq,
654            A: Allocator,
655        {
656            #[inline]
657            fn eq(&self, other: &$rhs) -> bool {
658                PartialEq::eq(&self[..], &other[..])
659            }
660
661            #[inline]
662            #[allow(clippy::partialeq_ne_impl)]
663            fn ne(&self, other: &$rhs) -> bool {
664                PartialEq::ne(&self[..], &other[..])
665            }
666        }
667
668        #[allow(unused_lifetimes)]
669        impl<'a, 'b, T, A> PartialEq<$lhs> for $rhs
670        where
671            T: PartialEq,
672            A: Allocator,
673        {
674            #[inline]
675            fn eq(&self, other: &$lhs) -> bool {
676                PartialEq::eq(&self[..], &other[..])
677            }
678
679            #[inline]
680            #[allow(clippy::partialeq_ne_impl)]
681            fn ne(&self, other: &$lhs) -> bool {
682                PartialEq::ne(&self[..], &other[..])
683            }
684        }
685    };
686}
687
688macro_rules! impl_eq_array {
689    ($lhs:ty, $rhs: ty) => {
690        #[allow(unused_lifetimes)]
691        impl<'a, 'b, T, A, const N: usize> PartialEq<$rhs> for $lhs
692        where
693            T: PartialEq,
694            A: Allocator,
695        {
696            #[inline]
697            fn eq(&self, other: &$rhs) -> bool {
698                PartialEq::eq(&self[..], &other[..])
699            }
700
701            #[inline]
702            #[allow(clippy::partialeq_ne_impl)]
703            fn ne(&self, other: &$rhs) -> bool {
704                PartialEq::ne(&self[..], &other[..])
705            }
706        }
707
708        #[allow(unused_lifetimes)]
709        impl<'a, 'b, T, A, const N: usize> PartialEq<$lhs> for $rhs
710        where
711            T: PartialEq,
712            A: Allocator,
713        {
714            #[inline]
715            fn eq(&self, other: &$lhs) -> bool {
716                PartialEq::eq(&self[..], &other[..])
717            }
718
719            #[inline]
720            #[allow(clippy::partialeq_ne_impl)]
721            fn ne(&self, other: &$lhs) -> bool {
722                PartialEq::ne(&self[..], &other[..])
723            }
724        }
725    };
726}
727
728impl_eq! { Vec<T, A>, [T] }
729impl_eq! { Vec<T, A>, &'a [T] }
730impl_eq_array! { Vec<T, A>, [T; N] }
731impl_eq_array! { Vec<T, A>, &'a [T; N] }
732
733impl<T, A, B> PartialEq<Vec<T, B>> for Vec<T, A>
734where
735    T: PartialEq,
736    A: Allocator,
737    B: Allocator,
738{
739    #[inline]
740    fn eq(&self, other: &Vec<T, B>) -> bool {
741        self.as_slice().eq(other.as_slice())
742    }
743}
744
745impl<T, A> Eq for Vec<T, A>
746where
747    T: Eq,
748    A: Allocator,
749{
750}
751
752impl<T, A, B> PartialOrd<Vec<T, B>> for Vec<T, A>
753where
754    T: PartialOrd,
755    A: Allocator,
756    B: Allocator,
757{
758    #[inline]
759    fn partial_cmp(&self, other: &Vec<T, B>) -> Option<Ordering> {
760        self.as_slice().partial_cmp(other.as_slice())
761    }
762}
763
764impl<T, A> Ord for Vec<T, A>
765where
766    T: Ord,
767    A: Allocator,
768{
769    #[inline]
770    fn cmp(&self, other: &Self) -> Ordering {
771        self.as_slice().cmp(other.as_slice())
772    }
773}
774
775impl<T, A> Borrow<[T]> for Vec<T, A>
776where
777    A: Allocator,
778{
779    #[inline]
780    fn borrow(&self) -> &[T] {
781        self
782    }
783}
784
785/// Conversion from a std [`Vec`][std-vec] to a Müsli-allocated [`Vec`] in the
786/// [`GlobalAllocator`] allocator.
787///
788/// [std-vec]: rust_alloc::vec::Vec
789///
790/// # Examples
791///
792/// ```
793/// use musli::alloc::{Vec, Global};
794///
795/// let values = vec![1, 2, 3, 4];
796/// let values2 = Vec::<_, Global>::from(values);
797/// ```
798#[cfg(feature = "alloc")]
799#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
800impl<T, A> From<rust_alloc::vec::Vec<T>> for Vec<T, A>
801where
802    A: GlobalAllocator,
803{
804    #[inline]
805    fn from(value: rust_alloc::vec::Vec<T>) -> Self {
806        use core::ptr::NonNull;
807
808        // SAFETY: We know that the vector was allocated as expected using the
809        // global allocator.
810        unsafe {
811            let mut value = ManuallyDrop::new(value);
812            let ptr = NonNull::new_unchecked(value.as_mut_ptr());
813            let len = value.len();
814            let cap = value.capacity();
815
816            let buf = A::slice_from_raw_parts(ptr, cap);
817            Vec::from_raw_parts(buf, len)
818        }
819    }
820}
821
822/// Decode implementation for a Müsli-allocated byte array stored in a [`Vec`].
823///
824/// # Examples
825///
826/// ```
827/// use musli::alloc::Vec;
828/// use musli::{Allocator, Decode};
829///
830/// #[derive(Decode)]
831/// struct Struct<A> where A: Allocator {
832///     #[musli(bytes)]
833///     field: Vec<u8, A>
834/// }
835/// ```
836impl<'de, M, A> DecodeBytes<'de, M, A> for Vec<u8, A>
837where
838    A: Allocator,
839{
840    const DECODE_BYTES_PACKED: bool = false;
841
842    #[inline]
843    fn decode_bytes<D>(decoder: D) -> Result<Self, D::Error>
844    where
845        D: Decoder<'de, Mode = M, Allocator = A>,
846    {
847        struct Visitor;
848
849        #[crate::trait_defaults(crate)]
850        impl<C> UnsizedVisitor<'_, C, [u8]> for Visitor
851        where
852            C: Context,
853        {
854            type Ok = Vec<u8, Self::Allocator>;
855
856            #[inline]
857            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858                write!(f, "bytes")
859            }
860
861            #[inline]
862            fn visit_owned(
863                self,
864                _: C,
865                value: Vec<u8, Self::Allocator>,
866            ) -> Result<Self::Ok, Self::Error> {
867                Ok(value)
868            }
869
870            #[inline]
871            fn visit_ref(self, cx: C, bytes: &[u8]) -> Result<Self::Ok, Self::Error> {
872                let mut buf = Vec::new_in(cx.alloc());
873                buf.extend_from_slice(bytes).map_err(cx.map())?;
874                Ok(buf)
875            }
876        }
877
878        decoder.decode_bytes(Visitor)
879    }
880}
881
882crate::internal::macros::slice_sequence! {
883    cx,
884    Vec<T, A>,
885    || Vec::new_in(cx.alloc()),
886    |vec, value| vec.push(value).map_err(cx.map())?,
887    |vec, capacity| vec.reserve(capacity).map_err(cx.map())?,
888    |capacity| Vec::with_capacity_in(capacity, cx.alloc()).map_err(cx.map())?,
889}