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