1use crate::num::NonMaxUsize;
16
17use super::{single_or_vec, AllocPtr, AllocSlice, AllocationError, IAlloc};
18use core::fmt::Debug;
19use core::ptr::NonNull;
20
21mod seal {
22 use super::*;
23 #[crate::stabby]
24 pub struct VecInner<T, Alloc: IAlloc> {
25 pub(crate) start: AllocPtr<T, Alloc>,
26 pub(crate) end: NonNull<T>,
27 pub(crate) capacity: NonNull<T>,
28 pub(crate) alloc: Alloc,
29 }
30 unsafe impl<T: Send, Alloc: IAlloc + Send> Send for VecInner<T, Alloc> where
32 crate::alloc::boxed::BoxedSlice<T, Alloc>: Send
33 {
34 }
35 unsafe impl<T: Sync, Alloc: IAlloc + Sync> Sync for VecInner<T, Alloc> where
37 crate::alloc::boxed::BoxedSlice<T, Alloc>: Sync
38 {
39 }
40}
41pub(crate) use seal::*;
42
43#[crate::stabby]
45pub struct Vec<T, Alloc: IAlloc = super::DefaultAllocator> {
46 pub(crate) inner: VecInner<T, Alloc>,
47}
48
49pub(crate) const fn ptr_diff<T>(lhs: NonNull<T>, rhs: NonNull<T>) -> usize {
50 let diff = if core::mem::size_of::<T>() == 0 {
51 unsafe { lhs.as_ptr().cast::<u8>().offset_from(rhs.as_ptr().cast()) }
52 } else {
53 unsafe { lhs.as_ptr().offset_from(rhs.as_ptr()) }
54 };
55 debug_assert!(diff >= 0);
56 diff as usize
57}
58pub(crate) const fn ptr_add<T>(lhs: NonNull<T>, rhs: usize) -> NonNull<T> {
59 if core::mem::size_of::<T>() == 0 {
60 unsafe { NonNull::new_unchecked(lhs.as_ptr().cast::<u8>().add(rhs)).cast() }
61 } else {
62 unsafe { NonNull::new_unchecked(lhs.as_ptr().add(rhs)) }
63 }
64}
65
66#[cfg(not(stabby_default_alloc = "disabled"))]
67impl<T> Vec<T> {
68 pub const fn new() -> Self {
70 Self::new_in(super::DefaultAllocator::new())
71 }
72}
73impl<T, Alloc: IAlloc> Vec<T, Alloc> {
74 pub const fn new_in(alloc: Alloc) -> Self {
76 let start = AllocPtr::dangling();
77 Self {
78 inner: VecInner {
79 start,
80 end: start.ptr,
81 capacity: if Self::zst_mode() {
82 unsafe { core::mem::transmute::<usize, NonNull<T>>(usize::MAX) }
83 } else {
84 start.ptr
85 },
86 alloc,
87 },
88 }
89 }
90 pub fn with_capacity_in(capacity: usize, alloc: Alloc) -> Self {
95 let mut this = Self::new_in(alloc);
96 this.reserve(capacity);
97 this
98 }
99 pub fn with_capacity(capacity: usize) -> Self
104 where
105 Alloc: Default,
106 {
107 Self::with_capacity_in(capacity, Alloc::default())
108 }
109 pub fn try_with_capacity_in(capacity: usize, alloc: Alloc) -> Result<Self, Alloc> {
113 let mut this = Self::new_in(alloc);
114 match this.try_reserve(capacity) {
115 Ok(_) => Ok(this),
116 Err(_) => Err(this.into_raw_components().2),
117 }
118 }
119 pub fn try_with_capacity(capacity: usize) -> Result<Self, Alloc>
123 where
124 Alloc: Default,
125 {
126 Self::try_with_capacity_in(capacity, Alloc::default())
127 }
128 #[inline(always)]
129 const fn zst_mode() -> bool {
130 core::mem::size_of::<T>() == 0
131 }
132 pub const fn len(&self) -> usize {
134 ptr_diff(self.inner.end, self.inner.start.ptr)
135 }
136 pub const fn is_empty(&self) -> bool {
138 self.len() == 0
139 }
140 #[rustversion::attr(since(1.86), const)]
144 pub unsafe fn set_len(&mut self, len: usize) {
145 self.inner.end = ptr_add(self.inner.start.ptr, len);
146 }
147 pub fn push(&mut self, value: T) {
152 if self.inner.end == self.inner.capacity {
153 self.grow();
154 }
155 unsafe { self.inner.end.as_ptr().write(value) }
156 self.inner.end = ptr_add(self.inner.end, 1)
157 }
158 pub fn try_push(&mut self, value: T) -> Result<(), T> {
166 if self.inner.end == self.inner.capacity && self.try_grow().is_err() {
167 return Err(value);
168 }
169 unsafe { self.inner.end.as_ptr().write(value) }
170 self.inner.end = ptr_add(self.inner.end, 1);
171 Ok(())
172 }
173 pub const fn capacity(&self) -> usize {
175 ptr_diff(self.inner.capacity, self.inner.start.ptr)
176 }
177 pub const fn remaining_capacity(&self) -> usize {
179 ptr_diff(self.inner.capacity, self.inner.end)
180 }
181 const FIRST_CAPACITY: usize = match 1024 / core::mem::size_of::<T>() {
182 0 => 1,
183 v @ 1..=8 => v,
184 _ => 8,
185 };
186 fn grow(&mut self) {
187 self.try_grow().unwrap();
188 }
189 fn try_grow(&mut self) -> Result<NonMaxUsize, AllocationError> {
190 if self.capacity() == 0 {
191 let first_capacity = Self::FIRST_CAPACITY;
192 self.try_reserve(first_capacity)
193 } else {
194 self.try_reserve((self.capacity() >> 1).max(1))
195 }
196 }
197 pub fn reserve(&mut self, additional: usize) {
204 self.try_reserve(additional).unwrap();
205 }
206 pub fn try_reserve(&mut self, additional: usize) -> Result<NonMaxUsize, AllocationError> {
214 if self.remaining_capacity() < additional {
215 let len = self.len();
216 let new_capacity = len.wrapping_add(additional);
217 let old_capacity = self.capacity();
218 let start = if old_capacity != 0 {
219 unsafe {
220 self.inner
221 .start
222 .realloc(&mut self.inner.alloc, old_capacity, new_capacity)
223 }
224 } else {
225 AllocPtr::alloc_array(&mut self.inner.alloc, new_capacity)
226 };
227 let Some(start) = start else {
228 return Err(AllocationError());
229 };
230 let end = ptr_add(*start, len);
231 let capacity = ptr_add(*start, new_capacity);
232 self.inner.start = start;
233 self.inner.end = end;
234 self.inner.capacity = capacity;
235 Ok(unsafe { NonMaxUsize::new_unchecked(new_capacity) })
236 } else {
237 let mut capacity = self.capacity();
238 if capacity == usize::MAX {
239 capacity = capacity.wrapping_sub(1);
240 }
241 Ok(unsafe { NonMaxUsize::new_unchecked(capacity) })
242 }
243 }
244 pub fn truncate(&mut self, len: usize) {
248 if let Some(to_drop) = self.get_mut(len..) {
249 unsafe {
251 core::ptr::drop_in_place(to_drop);
252 self.set_len(len);
253 }
254 }
255 }
256 pub const fn as_slice(&self) -> &[T] {
258 let start = self.inner.start;
259 let end = self.inner.end;
260 unsafe { core::slice::from_raw_parts(start.ptr.as_ptr(), ptr_diff(end, start.ptr)) }
261 }
262 #[rustversion::attr(since(1.86), const)]
264 pub fn as_slice_mut(&mut self) -> &mut [T] {
265 let start = self.inner.start;
266 let end = self.inner.end;
267 unsafe { core::slice::from_raw_parts_mut(start.ptr.as_ptr(), ptr_diff(end, start.ptr)) }
268 }
269 pub(crate) fn into_raw_components(self) -> (AllocSlice<T, Alloc>, usize, Alloc) {
270 let VecInner {
271 start,
272 end,
273 capacity: _,
274 alloc,
275 } = unsafe { core::ptr::read(&self.inner) };
276 let capacity = if core::mem::size_of::<T>() == 0 {
277 0
278 } else {
279 self.capacity()
280 };
281 core::mem::forget(self);
282 (AllocSlice { start, end }, capacity, alloc)
283 }
284 pub fn copy_extend(&mut self, slice: &[T])
289 where
290 T: Copy,
291 {
292 self.try_copy_extend(slice).unwrap();
293 }
294 pub fn try_copy_extend(&mut self, slice: &[T]) -> Result<(), AllocationError>
299 where
300 T: Copy,
301 {
302 if slice.is_empty() {
303 return Ok(());
304 }
305 self.try_reserve(slice.len())?;
306 unsafe {
307 core::ptr::copy_nonoverlapping(slice.as_ptr(), self.inner.end.as_ptr(), slice.len());
308 self.set_len(self.len().wrapping_add(slice.len()));
309 }
310 Ok(())
311 }
312 pub fn iter(&self) -> core::slice::Iter<'_, T> {
314 self.into_iter()
315 }
316 pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, T> {
318 self.into_iter()
319 }
320 pub fn drain<R: core::ops::RangeBounds<usize>>(&mut self, range: R) -> Drain<'_, T, Alloc> {
331 let original_len = self.len();
332 let from = match range.start_bound() {
333 core::ops::Bound::Included(i) => *i,
334 core::ops::Bound::Excluded(i) => i.wrapping_add(1),
335 core::ops::Bound::Unbounded => 0,
336 };
337 let to = match range.end_bound() {
338 core::ops::Bound::Included(i) => i.wrapping_add(1),
339 core::ops::Bound::Excluded(i) => *i,
340 core::ops::Bound::Unbounded => original_len,
341 };
342 assert!(to >= from);
343 assert!(to <= original_len);
344 unsafe { self.set_len(from) };
345 Drain {
346 vec: self,
347 from,
348 to,
349 index: from,
350 original_len,
351 }
352 }
353 pub fn try_drain<R: core::ops::RangeBounds<usize>>(
361 &mut self,
362 range: R,
363 ) -> Option<Drain<'_, T, Alloc>> {
364 let original_len = self.len();
365 let from = match range.start_bound() {
366 core::ops::Bound::Included(i) => *i,
367 core::ops::Bound::Excluded(i) => i.wrapping_add(1),
368 core::ops::Bound::Unbounded => 0,
369 };
370 let to = match range.end_bound() {
371 core::ops::Bound::Included(i) => i.wrapping_add(1),
372 core::ops::Bound::Excluded(i) => *i,
373 core::ops::Bound::Unbounded => original_len,
374 };
375 if to >= from || to <= original_len {
376 return None;
377 }
378 unsafe { self.set_len(from) };
379 Some(Drain {
380 vec: self,
381 from,
382 to,
383 index: from,
384 original_len,
385 })
386 }
387 #[rustversion::attr(since(1.86), const)]
389 pub fn remove(&mut self, index: usize) -> Option<T> {
390 if index < self.len() {
391 unsafe {
392 let value = self.inner.start.ptr.as_ptr().add(index).read();
393 core::ptr::copy(
394 self.inner.start.ptr.as_ptr().add(index.wrapping_add(1)),
395 self.inner.start.ptr.as_ptr().add(index),
396 self.len().wrapping_sub(index.wrapping_add(1)),
397 );
398 self.set_len(self.len().wrapping_sub(1));
399 Some(value)
400 }
401 } else {
402 None
403 }
404 }
405 pub fn swap(&mut self, a: usize, b: usize) {
410 assert!(a < self.len());
411 assert!(b < self.len());
412 unsafe {
413 core::ptr::swap(
414 self.inner.start.as_ptr().add(a),
415 self.inner.start.as_ptr().add(b),
416 )
417 };
418 }
419 #[rustversion::attr(since(1.86), const)]
421 pub fn pop(&mut self) -> Option<T> {
422 if self.is_empty() {
423 None
424 } else {
425 unsafe {
426 let value = self.inner.end.as_ptr().sub(1).read();
427 self.set_len(self.len().wrapping_sub(1));
428 Some(value)
429 }
430 }
431 }
432 pub fn swap_remove(&mut self, index: usize) -> Option<T> {
436 if index >= self.len() {
437 return None;
438 }
439 self.swap(index, self.len().wrapping_sub(1));
440 self.pop()
441 }
442 pub const fn allocator(&self) -> &Alloc {
444 &self.inner.alloc
445 }
446 #[rustversion::attr(since(1.86), const)]
448 pub fn allocator_mut(&mut self) -> &mut Alloc {
449 &mut self.inner.alloc
450 }
451}
452
453impl<T: Clone, Alloc: IAlloc + Clone> Clone for Vec<T, Alloc> {
454 fn clone(&self) -> Self {
455 let mut ret = Self::with_capacity_in(self.len(), self.inner.alloc.clone());
456 for (i, item) in self.iter().enumerate() {
457 unsafe { ret.inner.start.ptr.as_ptr().add(i).write(item.clone()) }
458 }
459 unsafe { ret.set_len(self.len()) };
460 ret
461 }
462}
463impl<T: PartialEq, Alloc: IAlloc, Rhs: AsRef<[T]>> PartialEq<Rhs> for Vec<T, Alloc> {
464 fn eq(&self, other: &Rhs) -> bool {
465 self.as_slice() == other.as_ref()
466 }
467}
468impl<T: Eq, Alloc: IAlloc> Eq for Vec<T, Alloc> {}
469impl<T: PartialOrd, Alloc: IAlloc, Rhs: AsRef<[T]>> PartialOrd<Rhs> for Vec<T, Alloc> {
470 fn partial_cmp(&self, other: &Rhs) -> Option<core::cmp::Ordering> {
471 self.as_slice().partial_cmp(other.as_ref())
472 }
473}
474impl<T: Ord, Alloc: IAlloc> Ord for Vec<T, Alloc> {
475 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
476 self.as_slice().cmp(other.as_slice())
477 }
478}
479
480use crate::{IDeterminantProvider, IStable};
481use single_or_vec::Single;
482
483macro_rules! impl_index {
484 ($index: ty) => {
485 impl<T, Alloc: IAlloc> core::ops::Index<$index> for Vec<T, Alloc> {
486 type Output = <[T] as core::ops::Index<$index>>::Output;
487 fn index(&self, index: $index) -> &Self::Output {
488 #[allow(clippy::indexing_slicing)]
489 &self.as_slice()[index]
490 }
491 }
492 impl<T, Alloc: IAlloc> core::ops::IndexMut<$index> for Vec<T, Alloc> {
493 fn index_mut(&mut self, index: $index) -> &mut Self::Output {
494 #[allow(clippy::indexing_slicing)]
495 &mut self.as_slice_mut()[index]
496 }
497 }
498 impl<T, Alloc: IAlloc> core::ops::Index<$index> for SingleOrVec<T, Alloc>
499 where
500 T: IStable,
501 Alloc: IStable,
502 Single<T, Alloc>: IDeterminantProvider<Vec<T, Alloc>>,
503 Vec<T, Alloc>: IStable,
504 crate::Result<Single<T, Alloc>, Vec<T, Alloc>>: IStable,
505 {
506 type Output = <[T] as core::ops::Index<$index>>::Output;
507 fn index(&self, index: $index) -> &Self::Output {
508 #[allow(clippy::indexing_slicing)]
509 &self.as_slice()[index]
510 }
511 }
512 };
513}
514
515impl<T, Alloc: IAlloc> core::ops::Deref for Vec<T, Alloc> {
516 type Target = [T];
517 fn deref(&self) -> &Self::Target {
518 self.as_slice()
519 }
520}
521impl<T, Alloc: IAlloc> core::convert::AsRef<[T]> for Vec<T, Alloc> {
522 fn as_ref(&self) -> &[T] {
523 self.as_slice()
524 }
525}
526impl<T, Alloc: IAlloc> core::ops::DerefMut for Vec<T, Alloc> {
527 fn deref_mut(&mut self) -> &mut Self::Target {
528 self.as_slice_mut()
529 }
530}
531impl<T, Alloc: IAlloc> core::convert::AsMut<[T]> for Vec<T, Alloc> {
532 fn as_mut(&mut self) -> &mut [T] {
533 self.as_slice_mut()
534 }
535}
536impl<T, Alloc: IAlloc + Default> Default for Vec<T, Alloc> {
537 fn default() -> Self {
538 Self::new_in(Alloc::default())
539 }
540}
541impl<T, Alloc: IAlloc> Drop for Vec<T, Alloc> {
542 fn drop(&mut self) {
543 unsafe { core::ptr::drop_in_place(self.as_slice_mut()) }
544 if core::mem::size_of::<T>() != 0 && self.capacity() != 0 {
545 unsafe { self.inner.start.free(&mut self.inner.alloc) }
546 }
547 }
548}
549impl<T: Copy, Alloc: IAlloc + Default> From<&[T]> for Vec<T, Alloc> {
550 fn from(value: &[T]) -> Self {
551 let mut this = Self::with_capacity(value.len());
552 this.copy_extend(value);
553 this
554 }
555}
556impl<T, Alloc: IAlloc> core::iter::Extend<T> for Vec<T, Alloc> {
557 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
558 let iter = iter.into_iter();
559 let (min, max) = iter.size_hint();
560 match max {
561 Some(max) => {
562 self.reserve(max);
563 iter.for_each(|item| {
564 unsafe { self.inner.end.as_ptr().write(item) };
565 self.inner.end = ptr_add(self.inner.end, 1);
566 })
567 }
568 _ => {
569 self.reserve(min);
570 iter.for_each(|item| self.push(item))
571 }
572 }
573 }
574}
575
576impl<T, Alloc: IAlloc + Default> core::iter::FromIterator<T> for Vec<T, Alloc> {
577 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
578 let mut ret = Self::default();
579 ret.extend(iter);
580 ret
581 }
582}
583
584impl_index!(usize);
585impl_index!(core::ops::Range<usize>);
586impl_index!(core::ops::RangeInclusive<usize>);
587impl_index!(core::ops::RangeTo<usize>);
588impl_index!(core::ops::RangeToInclusive<usize>);
589impl_index!(core::ops::RangeFrom<usize>);
590impl_index!(core::ops::RangeFull);
591
592impl<T: Debug, Alloc: IAlloc> Debug for Vec<T, Alloc> {
593 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
594 self.as_slice().fmt(f)
595 }
596}
597impl<T: core::fmt::LowerHex, Alloc: IAlloc> core::fmt::LowerHex for Vec<T, Alloc> {
598 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
599 let mut first = true;
600 for item in self {
601 if !first {
602 f.write_str(":")?;
603 }
604 first = false;
605 core::fmt::LowerHex::fmt(item, f)?;
606 }
607 Ok(())
608 }
609}
610impl<T: core::fmt::UpperHex, Alloc: IAlloc> core::fmt::UpperHex for Vec<T, Alloc> {
611 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
612 let mut first = true;
613 for item in self {
614 if !first {
615 f.write_str(":")?;
616 }
617 first = false;
618 core::fmt::UpperHex::fmt(item, f)?;
619 }
620 Ok(())
621 }
622}
623impl<'a, T, Alloc: IAlloc> IntoIterator for &'a Vec<T, Alloc> {
624 type Item = &'a T;
625 type IntoIter = core::slice::Iter<'a, T>;
626 fn into_iter(self) -> Self::IntoIter {
627 self.as_slice().iter()
628 }
629}
630impl<'a, T, Alloc: IAlloc> IntoIterator for &'a mut Vec<T, Alloc> {
631 type Item = &'a mut T;
632 type IntoIter = core::slice::IterMut<'a, T>;
633 fn into_iter(self) -> Self::IntoIter {
634 self.as_slice_mut().iter_mut()
635 }
636}
637impl<T, Alloc: IAlloc> IntoIterator for Vec<T, Alloc> {
638 type Item = T;
639 type IntoIter = IntoIter<T, Alloc>;
640 fn into_iter(self) -> Self::IntoIter {
641 IntoIter {
642 vec: self,
643 index: 0,
644 }
645 }
646}
647#[crate::stabby]
649pub struct IntoIter<T, Alloc: IAlloc> {
650 vec: Vec<T, Alloc>,
651 index: usize,
652}
653impl<T, Alloc: IAlloc> Iterator for IntoIter<T, Alloc> {
654 type Item = T;
655 fn next(&mut self) -> Option<Self::Item> {
656 (self.index < self.vec.len()).then(|| unsafe {
657 let ret = self.vec.inner.start.as_ptr().add(self.index).read();
658 self.index = self.index.wrapping_add(1);
659 ret
660 })
661 }
662}
663impl<T, Alloc: IAlloc> Drop for IntoIter<T, Alloc> {
664 fn drop(&mut self) {
665 unsafe {
666 #[allow(clippy::indexing_slicing)]
667 core::ptr::drop_in_place(&mut self.vec.as_slice_mut()[self.index..]);
668 self.vec.set_len(0);
669 }
670 }
671}
672#[crate::stabby]
679pub struct Drain<'a, T: 'a, Alloc: IAlloc + 'a> {
680 vec: &'a mut Vec<T, Alloc>,
681 from: usize,
682 to: usize,
683 index: usize,
684 original_len: usize,
685}
686impl<'a, T: 'a, Alloc: IAlloc + 'a> Drain<'a, T, Alloc> {
687 pub fn stop(mut self) {
690 self.to = self.index
691 }
692 #[rustversion::attr(since(1.86), const)]
694 pub fn double_ended(self) -> DoubleEndedDrain<'a, T, Alloc> {
695 let ret = DoubleEndedDrain {
696 vec: unsafe { core::ptr::read(&self.vec) },
697 from: self.from,
698 to: self.to,
699 original_len: self.original_len,
700 lindex: self.index,
701 rindex: self.to,
702 };
703 core::mem::forget(self);
704 ret
705 }
706}
707impl<'a, T: 'a, Alloc: IAlloc + 'a> Iterator for Drain<'a, T, Alloc> {
708 type Item = T;
709 fn size_hint(&self) -> (usize, Option<usize>) {
710 let remaining = self.to.wrapping_sub(self.index);
711 (remaining, Some(remaining))
712 }
713 fn next(&mut self) -> Option<Self::Item> {
714 (self.index < self.to).then(|| unsafe {
715 let ret = self.vec.inner.start.as_ptr().add(self.index).read();
716 self.index = self.index.wrapping_add(1);
717 ret
718 })
719 }
720}
721impl<'a, T: 'a, Alloc: IAlloc + 'a> ExactSizeIterator for Drain<'a, T, Alloc> {
722 fn len(&self) -> usize {
723 self.to.wrapping_sub(self.index)
724 }
725}
726impl<'a, T: 'a, Alloc: IAlloc + 'a> Drop for Drain<'a, T, Alloc> {
727 fn drop(&mut self) {
728 let tail_length = self.original_len.wrapping_sub(self.to);
729 unsafe {
730 core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
731 self.vec.inner.start.as_ptr().add(self.index),
732 self.to.wrapping_sub(self.index),
733 ));
734 core::ptr::copy(
735 self.vec.inner.start.as_ptr().add(self.to),
736 self.vec.inner.start.as_ptr().add(self.from),
737 tail_length,
738 );
739 self.vec.set_len(tail_length.wrapping_add(self.from));
740 }
741 }
742}
743#[crate::stabby]
745pub struct DoubleEndedDrain<'a, T: 'a, Alloc: IAlloc + 'a> {
746 vec: &'a mut Vec<T, Alloc>,
747 from: usize,
748 to: usize,
749 original_len: usize,
750 lindex: usize,
751 rindex: usize,
752}
753impl<'a, T: 'a, Alloc: IAlloc + 'a> Iterator for DoubleEndedDrain<'a, T, Alloc> {
754 type Item = T;
755 fn size_hint(&self) -> (usize, Option<usize>) {
756 let remaining = self.to.wrapping_sub(self.lindex);
757 (remaining, Some(remaining))
758 }
759 fn next(&mut self) -> Option<Self::Item> {
760 (self.lindex < self.rindex).then(|| unsafe {
761 let ret = self.vec.inner.start.as_ptr().add(self.lindex).read();
762 self.lindex = self.lindex.wrapping_add(1);
763 ret
764 })
765 }
766}
767impl<'a, T: 'a, Alloc: IAlloc + 'a> DoubleEndedIterator for DoubleEndedDrain<'a, T, Alloc> {
768 fn next_back(&mut self) -> Option<Self::Item> {
769 (self.lindex < self.rindex).then(|| unsafe {
770 let ret = self.vec.inner.start.as_ptr().add(self.rindex).read();
771 self.rindex = self.rindex.wrapping_sub(1);
772 ret
773 })
774 }
775}
776impl<'a, T: 'a, Alloc: IAlloc + 'a> ExactSizeIterator for DoubleEndedDrain<'a, T, Alloc> {
777 fn len(&self) -> usize {
778 self.rindex.wrapping_sub(self.lindex)
779 }
780}
781impl<'a, T: 'a, Alloc: IAlloc + 'a> Drop for DoubleEndedDrain<'a, T, Alloc> {
782 fn drop(&mut self) {
783 let tail_length = self.original_len.wrapping_sub(self.to);
784 unsafe {
785 core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
786 self.vec.inner.start.as_ptr().add(self.lindex),
787 self.rindex.wrapping_sub(self.lindex),
788 ));
789 core::ptr::copy(
790 self.vec.inner.start.as_ptr().add(self.to),
791 self.vec.inner.start.as_ptr().add(self.from),
792 tail_length,
793 );
794 self.vec.set_len(tail_length.wrapping_add(self.from));
795 }
796 }
797}
798#[cfg(feature = "std")]
799impl<Alloc: IAlloc> std::io::Write for Vec<u8, Alloc> {
800 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
801 match self.try_copy_extend(buf) {
802 Ok(()) => Ok(buf.len()),
803 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::OutOfMemory, e)),
804 }
805 }
806
807 fn flush(&mut self) -> std::io::Result<()> {
808 Ok(())
809 }
810}
811
812#[cfg(feature = "std")]
813#[test]
814fn test() {
815 use rand::Rng;
816 const LEN: usize = 2000;
817 let mut std = std::vec::Vec::with_capacity(LEN);
818 let mut new: Vec<u8> = Vec::new();
819 let mut capacity: Vec<u8> = Vec::with_capacity(LEN);
820 let mut rng = rand::thread_rng();
821 for _ in 0..LEN {
822 let n: u8 = rng.gen();
823 new.push(n);
824 capacity.push(n);
825 std.push(n);
826 }
827 assert_eq!(new.as_slice(), std.as_slice());
828 assert_eq!(new.as_slice(), capacity.as_slice());
829 new.drain(55..100);
830 capacity.drain(55..100);
831 std.drain(55..100);
832 new.swap(5, 92);
833 std.swap(5, 92);
834 capacity.swap(5, 92);
835 assert_eq!(new.as_slice(), std.as_slice());
836 assert_eq!(new.as_slice(), capacity.as_slice());
837}
838
839pub use super::single_or_vec::SingleOrVec;
840
841#[cfg(feature = "serde")]
842mod serde_impl {
843 use super::*;
844 use crate::alloc::IAlloc;
845 use serde::{de::Visitor, Deserialize, Serialize};
846 impl<T: Serialize, Alloc: IAlloc> Serialize for Vec<T, Alloc> {
847 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
848 where
849 S: serde::Serializer,
850 {
851 let slice: &[T] = self;
852 slice.serialize(serializer)
853 }
854 }
855 impl<'a, T: Deserialize<'a>, Alloc: IAlloc + Default> Deserialize<'a> for Vec<T, Alloc> {
856 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
857 where
858 D: serde::Deserializer<'a>,
859 {
860 deserializer.deserialize_seq(VecVisitor(core::marker::PhantomData))
861 }
862 }
863 pub struct VecVisitor<T, Alloc>(core::marker::PhantomData<(T, Alloc)>);
864 impl<'a, T: Deserialize<'a>, Alloc: IAlloc + Default> Visitor<'a> for VecVisitor<T, Alloc> {
865 type Value = Vec<T, Alloc>;
866 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
867 formatter.write_str("A sequence")
868 }
869 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
870 where
871 A: serde::de::SeqAccess<'a>,
872 {
873 let mut this = Vec::with_capacity_in(seq.size_hint().unwrap_or(0), Alloc::default());
874 while let Some(v) = seq.next_element()? {
875 this.push(v);
876 }
877 Ok(this)
878 }
879 }
880}