1use super::*;
2use core::convert::{TryFrom, TryInto};
3
4#[cfg(feature = "serde")]
5use core::marker::PhantomData;
6#[cfg(feature = "serde")]
7use serde_core::de::{
8 Deserialize, Deserializer, Error as DeserializeError, SeqAccess, Visitor,
9};
10#[cfg(feature = "serde")]
11use serde_core::ser::{Serialize, SerializeSeq, Serializer};
12
13#[macro_export]
30macro_rules! array_vec {
31 ($array_type:ty => $($elem:expr),* $(,)?) => {
32 {
33 let mut av: $crate::ArrayVec<$array_type> = Default::default();
34 $( av.push($elem); )*
35 av
36 }
37 };
38 ($array_type:ty) => {
39 $crate::ArrayVec::<$array_type>::default()
40 };
41 ($($elem:expr),*) => {
42 $crate::array_vec!(_ => $($elem),*)
43 };
44 ($elem:expr; $n:expr) => {
45 $crate::ArrayVec::from([$elem; $n])
46 };
47 () => {
48 $crate::array_vec!(_)
49 };
50}
51
52#[repr(C)]
106pub struct ArrayVec<A> {
107 len: u16,
108 pub(crate) data: A,
109}
110
111impl<A> Clone for ArrayVec<A>
112where
113 A: Array + Clone,
114 A::Item: Clone,
115{
116 #[inline]
117 fn clone(&self) -> Self {
118 Self { data: self.data.clone(), len: self.len }
119 }
120
121 #[inline]
122 fn clone_from(&mut self, o: &Self) {
123 let iter = self
124 .data
125 .as_slice_mut()
126 .iter_mut()
127 .zip(o.data.as_slice())
128 .take(self.len.max(o.len) as usize);
129 for (dst, src) in iter {
130 dst.clone_from(src)
131 }
132 if let Some(to_drop) =
133 self.data.as_slice_mut().get_mut((o.len as usize)..(self.len as usize))
134 {
135 to_drop.iter_mut().for_each(|x| drop(core::mem::take(x)));
136 }
137 self.len = o.len;
138 }
139}
140
141impl<A> Copy for ArrayVec<A>
142where
143 A: Array + Copy,
144 A::Item: Copy,
145{
146}
147
148impl<A: Array> Default for ArrayVec<A> {
149 #[inline]
150 fn default() -> Self {
151 Self { len: 0, data: A::default() }
152 }
153}
154
155impl<A: Array> Deref for ArrayVec<A> {
156 type Target = [A::Item];
157 #[inline(always)]
158 fn deref(&self) -> &Self::Target {
159 &self.data.as_slice()[..self.len as usize]
160 }
161}
162
163impl<A: Array> DerefMut for ArrayVec<A> {
164 #[inline(always)]
165 fn deref_mut(&mut self) -> &mut Self::Target {
166 &mut self.data.as_slice_mut()[..self.len as usize]
167 }
168}
169
170impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for ArrayVec<A> {
171 type Output = <I as SliceIndex<[A::Item]>>::Output;
172 #[inline(always)]
173 fn index(&self, index: I) -> &Self::Output {
174 &self.deref()[index]
175 }
176}
177
178impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for ArrayVec<A> {
179 #[inline(always)]
180 fn index_mut(&mut self, index: I) -> &mut Self::Output {
181 &mut self.deref_mut()[index]
182 }
183}
184
185#[cfg(feature = "serde")]
186#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
187impl<A: Array> Serialize for ArrayVec<A>
188where
189 A::Item: Serialize,
190{
191 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
192 where
193 S: Serializer,
194 {
195 let mut seq = serializer.serialize_seq(Some(self.len()))?;
196 for element in self.iter() {
197 seq.serialize_element(element)?;
198 }
199 seq.end()
200 }
201}
202
203#[cfg(feature = "serde")]
204#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
205impl<'de, A: Array> Deserialize<'de> for ArrayVec<A>
206where
207 A::Item: Deserialize<'de>,
208{
209 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210 where
211 D: Deserializer<'de>,
212 {
213 deserializer.deserialize_seq(ArrayVecVisitor(PhantomData))
214 }
215}
216
217#[cfg(feature = "borsh")]
218#[cfg_attr(docs_rs, doc(cfg(feature = "borsh")))]
219impl<A: Array> borsh::BorshSerialize for ArrayVec<A>
220where
221 <A as Array>::Item: borsh::BorshSerialize,
222{
223 fn serialize<W: borsh::io::Write>(
224 &self, writer: &mut W,
225 ) -> borsh::io::Result<()> {
226 <usize as borsh::BorshSerialize>::serialize(&self.len(), writer)?;
227 for elem in self.iter() {
228 <<A as Array>::Item as borsh::BorshSerialize>::serialize(elem, writer)?;
229 }
230 Ok(())
231 }
232}
233
234#[cfg(feature = "borsh")]
235#[cfg_attr(docs_rs, doc(cfg(feature = "borsh")))]
236impl<A: Array> borsh::BorshDeserialize for ArrayVec<A>
237where
238 <A as Array>::Item: borsh::BorshDeserialize,
239{
240 fn deserialize_reader<R: borsh::io::Read>(
241 reader: &mut R,
242 ) -> borsh::io::Result<Self> {
243 let len = <usize as borsh::BorshDeserialize>::deserialize_reader(reader)?;
244 let mut new_arrayvec = Self::default();
245
246 for idx in 0..len {
247 let value =
248 <<A as Array>::Item as borsh::BorshDeserialize>::deserialize_reader(
249 reader,
250 )?;
251 if idx >= new_arrayvec.capacity() {
252 return Err(borsh::io::Error::new(
253 borsh::io::ErrorKind::InvalidData,
254 "invalid ArrayVec length",
255 ));
256 }
257 new_arrayvec.push(value)
258 }
259
260 Ok(new_arrayvec)
261 }
262}
263
264#[cfg(feature = "arbitrary")]
265#[cfg_attr(docs_rs, doc(cfg(feature = "arbitrary")))]
266impl<'a, A> arbitrary::Arbitrary<'a> for ArrayVec<A>
267where
268 A: Array,
269 A::Item: arbitrary::Arbitrary<'a>,
270{
271 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
272 let max_len = A::CAPACITY.min(u16::MAX as usize) as u16;
273 let len = u.int_in_range::<u16>(0..=max_len)?;
274 let mut self_: Self = Default::default();
275 for _ in 0..len {
276 self_.push(u.arbitrary()?);
277 }
278 Ok(self_)
279 }
280
281 fn size_hint(depth: usize) -> (usize, Option<usize>) {
282 arbitrary::size_hint::recursion_guard(depth, |depth| {
283 let max_len = A::CAPACITY.min(u16::MAX as usize);
284 let inner = A::Item::size_hint(depth).1;
285 (0, inner.map(|inner| 2 + max_len * inner))
286 })
287 }
288}
289
290#[cfg(feature = "bin-proto")]
291#[cfg_attr(docs_rs, doc(cfg(feature = "bin-proto")))]
292impl<Ctx, A> bin_proto::BitEncode<Ctx, bin_proto::Untagged> for ArrayVec<A>
293where
294 A: Array,
295 <A as Array>::Item: bin_proto::BitEncode<Ctx>,
296{
297 fn encode<W, E>(
298 &self, write: &mut W, ctx: &mut Ctx, tag: bin_proto::Untagged,
299 ) -> bin_proto::Result<()>
300 where
301 W: bin_proto::BitWrite,
302 E: bin_proto::Endianness,
303 {
304 <[<A as Array>::Item] as bin_proto::BitEncode<_, _>>::encode::<_, E>(
305 self.as_slice(),
306 write,
307 ctx,
308 tag,
309 )
310 }
311}
312
313#[cfg(feature = "bin-proto")]
314#[cfg_attr(docs_rs, doc(cfg(feature = "bin-proto")))]
315impl<Tag, Ctx, A> bin_proto::BitDecode<Ctx, bin_proto::Tag<Tag>> for ArrayVec<A>
316where
317 A: Array,
318 <A as Array>::Item: bin_proto::BitDecode<Ctx>,
319 Tag: ::core::convert::TryInto<usize>,
320{
321 fn decode<R, E>(
322 read: &mut R, ctx: &mut Ctx, tag: bin_proto::Tag<Tag>,
323 ) -> bin_proto::Result<Self>
324 where
325 R: bin_proto::BitRead,
326 E: bin_proto::Endianness,
327 {
328 let item_count =
329 tag.0.try_into().map_err(|_| bin_proto::Error::TagConvert)?;
330 if item_count > A::CAPACITY {
331 return Err(bin_proto::Error::Other("insufficient capacity"));
332 }
333 let mut values = Self::default();
334 for _ in 0..item_count {
335 values.push(bin_proto::BitDecode::<_, _>::decode::<_, E>(read, ctx, ())?);
336 }
337 Ok(values)
338 }
339}
340
341#[cfg(feature = "bin-proto")]
342#[cfg_attr(docs_rs, doc(cfg(feature = "bin-proto")))]
343impl<Ctx, A> bin_proto::BitDecode<Ctx, bin_proto::Untagged> for ArrayVec<A>
344where
345 A: Array,
346 <A as Array>::Item: bin_proto::BitDecode<Ctx>,
347{
348 fn decode<R, E>(
349 read: &mut R, ctx: &mut Ctx, _tag: bin_proto::Untagged,
350 ) -> bin_proto::Result<Self>
351 where
352 R: bin_proto::BitRead,
353 E: bin_proto::Endianness,
354 {
355 let mut values = Self::default();
356 for item in bin_proto::util::decode_items_to_eof::<_, E, _, _>(read, ctx) {
357 if values.try_push(item?).is_some() {
358 return Err(bin_proto::Error::Other("insufficient capacity"));
359 }
360 }
361 Ok(values)
362 }
363}
364
365#[cfg(feature = "schemars")]
366#[cfg_attr(docs_rs, doc(cfg(feature = "schemars")))]
367impl<A> schemars::JsonSchema for ArrayVec<A>
368where
369 A: Array,
370 <A as Array>::Item: schemars::JsonSchema,
371{
372 fn schema_name() -> alloc::borrow::Cow<'static, str> {
373 alloc::format!(
374 "Array_up_to_size_{}_of_{}",
375 A::CAPACITY,
376 <A as Array>::Item::schema_name()
377 )
378 .into()
379 }
380
381 fn json_schema(
382 generator: &mut schemars::SchemaGenerator,
383 ) -> schemars::Schema {
384 schemars::json_schema!({
385 "type": "array",
386 "items": generator.subschema_for::<<A as Array>::Item>(),
387 "maxItems": A::CAPACITY
388 })
389 }
390}
391
392impl<A: Array> ArrayVec<A> {
393 #[inline]
408 pub fn append(&mut self, other: &mut Self) {
409 assert!(
410 self.try_append(other).is_none(),
411 "ArrayVec::append> total length {} exceeds capacity {}!",
412 self.len() + other.len(),
413 A::CAPACITY
414 );
415 }
416
417 #[inline]
434 pub fn try_append<'other>(
435 &mut self, other: &'other mut Self,
436 ) -> Option<&'other mut Self> {
437 let new_len = self.len() + other.len();
438 if new_len > A::CAPACITY {
439 return Some(other);
440 }
441
442 let iter = other.iter_mut().map(core::mem::take);
443 for item in iter {
444 self.push(item);
445 }
446
447 other.set_len(0);
448
449 return None;
450 }
451
452 #[inline(always)]
458 #[must_use]
459 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
460 self.data.as_slice_mut().as_mut_ptr()
461 }
462
463 #[inline(always)]
465 #[must_use]
466 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
467 self.deref_mut()
468 }
469
470 #[inline(always)]
476 #[must_use]
477 pub fn as_ptr(&self) -> *const A::Item {
478 self.data.as_slice().as_ptr()
479 }
480
481 #[inline(always)]
483 #[must_use]
484 pub fn as_slice(&self) -> &[A::Item] {
485 self.deref()
486 }
487
488 #[inline(always)]
493 #[must_use]
494 pub fn capacity(&self) -> usize {
495 self.data.as_slice().len().min(u16::MAX as usize)
499 }
500
501 #[inline(always)]
503 pub fn clear(&mut self) {
504 self.truncate(0)
505 }
506
507 #[inline]
526 pub fn drain<R>(&mut self, range: R) -> ArrayVecDrain<'_, A::Item>
527 where
528 R: RangeBounds<usize>,
529 {
530 ArrayVecDrain::new(self, range)
531 }
532
533 #[inline]
559 pub fn into_inner(self) -> A {
560 self.data
561 }
562
563 #[inline]
568 pub fn extend_from_slice(&mut self, sli: &[A::Item])
569 where
570 A::Item: Clone,
571 {
572 if sli.is_empty() {
573 return;
574 }
575
576 let new_len = self.len as usize + sli.len();
577 assert!(
578 new_len <= A::CAPACITY,
579 "ArrayVec::extend_from_slice> total length {} exceeds capacity {}!",
580 new_len,
581 A::CAPACITY
582 );
583
584 let target = &mut self.data.as_slice_mut()[self.len as usize..new_len];
585 target.clone_from_slice(sli);
586 self.set_len(new_len);
587 }
588
589 #[inline]
615 pub fn fill<I: IntoIterator<Item = A::Item>>(
616 &mut self, iter: I,
617 ) -> I::IntoIter {
618 let mut iter = iter.into_iter();
623 let mut pushed = 0;
624 let to_take = self.capacity() - self.len();
625 let target = &mut self.data.as_slice_mut()[self.len as usize..];
626 for element in iter.by_ref().take(to_take) {
627 target[pushed] = element;
628 pushed += 1;
629 }
630 self.len += pushed as u16;
631 iter
632 }
633
634 #[inline]
643 #[must_use]
644 #[allow(clippy::match_wild_err_arm)]
645 pub fn from_array_len(data: A, len: usize) -> Self {
646 match Self::try_from_array_len(data, len) {
647 Ok(out) => out,
648 Err(_) => panic!(
649 "ArrayVec::from_array_len> length {} exceeds capacity {}!",
650 len,
651 A::CAPACITY
652 ),
653 }
654 }
655
656 #[inline]
673 pub fn insert(&mut self, index: usize, item: A::Item) {
674 let x = self.try_insert(index, item);
675 assert!(x.is_none(), "ArrayVec::insert> capacity overflow!");
676 }
677
678 #[inline]
695 pub fn try_insert(
696 &mut self, index: usize, mut item: A::Item,
697 ) -> Option<A::Item> {
698 assert!(
699 index <= self.len as usize,
700 "ArrayVec::try_insert> index {} is out of bounds {}",
701 index,
702 self.len
703 );
704
705 if (self.len as usize) < A::CAPACITY {
713 self.len += 1;
714 } else {
715 return Some(item);
716 }
717
718 let target = &mut self.as_mut_slice()[index..];
719 #[allow(clippy::needless_range_loop)]
720 for i in 0..target.len() {
721 core::mem::swap(&mut item, &mut target[i]);
722 }
723 return None;
724 }
725
726 #[inline(always)]
728 #[must_use]
729 pub fn is_empty(&self) -> bool {
730 self.len == 0
731 }
732
733 #[inline(always)]
735 #[must_use]
736 pub fn is_full(&self) -> bool {
737 self.len() == self.capacity()
738 }
739
740 #[inline(always)]
742 #[must_use]
743 pub fn len(&self) -> usize {
744 self.len as usize
745 }
746
747 #[inline(always)]
749 #[must_use]
750 pub fn new() -> Self {
751 Self::default()
752 }
753
754 #[inline]
768 pub fn pop(&mut self) -> Option<A::Item> {
769 if self.len > 0 {
770 self.len -= 1;
771 let out =
772 core::mem::take(&mut self.data.as_slice_mut()[self.len as usize]);
773 Some(out)
774 } else {
775 None
776 }
777 }
778
779 #[inline(always)]
796 pub fn push(&mut self, val: A::Item) {
797 let x = self.try_push(val);
798 assert!(x.is_none(), "ArrayVec::push> capacity overflow!");
799 }
800
801 #[inline(always)]
815 pub fn try_push(&mut self, val: A::Item) -> Option<A::Item> {
816 debug_assert!(self.len as usize <= A::CAPACITY);
817
818 let itemref = match self.data.as_slice_mut().get_mut(self.len as usize) {
819 None => return Some(val),
820 Some(x) => x,
821 };
822
823 *itemref = val;
824 self.len += 1;
825 return None;
826 }
827
828 #[inline]
845 pub fn remove(&mut self, index: usize) -> A::Item {
846 let targets: &mut [A::Item] = &mut self.deref_mut()[index..];
847 let item = core::mem::take(&mut targets[0]);
848
849 for i in 0..targets.len() - 1 {
857 targets.swap(i, i + 1);
858 }
859 self.len -= 1;
860 item
861 }
862
863 #[inline]
880 pub fn resize(&mut self, new_len: usize, new_val: A::Item)
881 where
882 A::Item: Clone,
883 {
884 self.resize_with(new_len, || new_val.clone())
885 }
886
887 #[inline]
910 pub fn resize_with<F: FnMut() -> A::Item>(
911 &mut self, new_len: usize, mut f: F,
912 ) {
913 match new_len.checked_sub(self.len as usize) {
914 None => self.truncate(new_len),
915 Some(new_elements) => {
916 for _ in 0..new_elements {
917 self.push(f());
918 }
919 }
920 }
921 }
922
923 #[inline]
935 pub fn retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F) {
936 struct JoinOnDrop<'vec, Item> {
939 items: &'vec mut [Item],
940 done_end: usize,
941 tail_start: usize,
943 }
944
945 impl<Item> Drop for JoinOnDrop<'_, Item> {
946 fn drop(&mut self) {
947 self.items[self.done_end..].rotate_left(self.tail_start);
948 }
949 }
950
951 let mut rest = JoinOnDrop {
952 items: &mut self.data.as_slice_mut()[..self.len as usize],
953 done_end: 0,
954 tail_start: 0,
955 };
956
957 let len = self.len as usize;
958 for idx in 0..len {
959 if !acceptable(&rest.items[idx]) {
961 let _ = core::mem::take(&mut rest.items[idx]);
962 self.len -= 1;
963 rest.tail_start += 1;
964 } else {
965 rest.items.swap(rest.done_end, idx);
966 rest.done_end += 1;
967 }
968 }
969 }
970
971 #[inline]
989 pub fn retain_mut<F>(&mut self, mut acceptable: F)
990 where
991 F: FnMut(&mut A::Item) -> bool,
992 {
993 struct JoinOnDrop<'vec, Item> {
996 items: &'vec mut [Item],
997 done_end: usize,
998 tail_start: usize,
1000 }
1001
1002 impl<Item> Drop for JoinOnDrop<'_, Item> {
1003 fn drop(&mut self) {
1004 self.items[self.done_end..].rotate_left(self.tail_start);
1005 }
1006 }
1007
1008 let mut rest = JoinOnDrop {
1009 items: &mut self.data.as_slice_mut()[..self.len as usize],
1010 done_end: 0,
1011 tail_start: 0,
1012 };
1013
1014 let len = self.len as usize;
1015 for idx in 0..len {
1016 if !acceptable(&mut rest.items[idx]) {
1018 let _ = core::mem::take(&mut rest.items[idx]);
1019 self.len -= 1;
1020 rest.tail_start += 1;
1021 } else {
1022 rest.items.swap(rest.done_end, idx);
1023 rest.done_end += 1;
1024 }
1025 }
1026 }
1027
1028 #[inline(always)]
1039 pub fn set_len(&mut self, new_len: usize) {
1040 if new_len > A::CAPACITY {
1041 panic!(
1046 "ArrayVec::set_len> new length {} exceeds capacity {}",
1047 new_len,
1048 A::CAPACITY
1049 )
1050 }
1051
1052 let new_len: u16 = new_len
1053 .try_into()
1054 .expect("ArrayVec::set_len> new length is not in range 0..=u16::MAX");
1055 self.len = new_len;
1056 }
1057
1058 #[inline]
1076 pub fn split_off(&mut self, at: usize) -> Self {
1077 if at > self.len() {
1079 panic!(
1080 "ArrayVec::split_off> at value {} exceeds length of {}",
1081 at, self.len
1082 );
1083 }
1084 let mut new = Self::default();
1085 let moves = &mut self.as_mut_slice()[at..];
1086 let split_len = moves.len();
1087 let targets = &mut new.data.as_slice_mut()[..split_len];
1088 moves.swap_with_slice(targets);
1089
1090 new.len = split_len as u16;
1092 self.len = at as u16;
1093 new
1094 }
1095
1096 #[inline]
1123 pub fn splice<R, I>(
1124 &mut self, range: R, replacement: I,
1125 ) -> ArrayVecSplice<'_, A, core::iter::Fuse<I::IntoIter>>
1126 where
1127 R: RangeBounds<usize>,
1128 I: IntoIterator<Item = A::Item>,
1129 {
1130 use core::ops::Bound;
1131 let start = match range.start_bound() {
1132 Bound::Included(x) => *x,
1133 Bound::Excluded(x) => x.saturating_add(1),
1134 Bound::Unbounded => 0,
1135 };
1136 let end = match range.end_bound() {
1137 Bound::Included(x) => x.saturating_add(1),
1138 Bound::Excluded(x) => *x,
1139 Bound::Unbounded => self.len(),
1140 };
1141 assert!(
1142 start <= end,
1143 "ArrayVec::splice> Illegal range, {} to {}",
1144 start,
1145 end
1146 );
1147 assert!(
1148 end <= self.len(),
1149 "ArrayVec::splice> Range ends at {} but length is only {}!",
1150 end,
1151 self.len()
1152 );
1153
1154 ArrayVecSplice {
1155 removal_start: start,
1156 removal_end: end,
1157 parent: self,
1158 replacement: replacement.into_iter().fuse(),
1159 }
1160 }
1161
1162 #[inline]
1179 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1180 assert!(
1181 index < self.len(),
1182 "ArrayVec::swap_remove> index {} is out of bounds {}",
1183 index,
1184 self.len
1185 );
1186 if index == self.len() - 1 {
1187 self.pop().unwrap()
1188 } else {
1189 let i = self.pop().unwrap();
1190 replace(&mut self[index], i)
1191 }
1192 }
1193
1194 #[inline]
1198 pub fn truncate(&mut self, new_len: usize) {
1199 if new_len >= self.len as usize {
1200 return;
1201 }
1202
1203 if needs_drop::<A::Item>() {
1204 let len = self.len as usize;
1205 self.data.as_slice_mut()[new_len..len]
1206 .iter_mut()
1207 .map(core::mem::take)
1208 .for_each(drop);
1209 }
1210
1211 self.len = new_len as u16;
1213 }
1214
1215 #[inline]
1225 #[cfg(not(feature = "latest_stable_rust"))]
1226 pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1227 if len <= A::CAPACITY {
1229 Ok(Self { data, len: len as u16 })
1230 } else {
1231 Err(data)
1232 }
1233 }
1234
1235 #[inline]
1245 #[cfg(feature = "latest_stable_rust")]
1246 pub const fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1247 if len <= A::CAPACITY {
1249 Ok(Self { data, len: len as u16 })
1250 } else {
1251 Err(data)
1252 }
1253 }
1254}
1255
1256impl<A> ArrayVec<A> {
1257 #[inline]
1281 #[must_use]
1282 pub const fn from_array_empty(data: A) -> Self {
1283 Self { data, len: 0 }
1284 }
1285}
1286
1287#[cfg(feature = "grab_spare_slice")]
1288impl<A: Array> ArrayVec<A> {
1289 #[inline(always)]
1303 pub fn grab_spare_slice(&self) -> &[A::Item] {
1304 &self.data.as_slice()[self.len as usize..]
1305 }
1306
1307 #[inline(always)]
1319 pub fn grab_spare_slice_mut(&mut self) -> &mut [A::Item] {
1320 &mut self.data.as_slice_mut()[self.len as usize..]
1321 }
1322}
1323
1324#[cfg(feature = "nightly_slice_partition_dedup")]
1325impl<A: Array> ArrayVec<A> {
1326 #[inline(always)]
1328 pub fn dedup(&mut self)
1329 where
1330 A::Item: PartialEq,
1331 {
1332 self.dedup_by(|a, b| a == b)
1333 }
1334
1335 #[inline(always)]
1337 pub fn dedup_by<F>(&mut self, same_bucket: F)
1338 where
1339 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1340 {
1341 let len = {
1342 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1343 dedup.len()
1344 };
1345 self.truncate(len);
1346 }
1347
1348 #[inline(always)]
1350 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1351 where
1352 F: FnMut(&mut A::Item) -> K,
1353 K: PartialEq,
1354 {
1355 self.dedup_by(|a, b| key(a) == key(b))
1356 }
1357}
1358
1359impl<A> ArrayVec<A> {
1360 #[inline(always)]
1365 #[must_use]
1366 pub const fn as_inner(&self) -> &A {
1367 &self.data
1368 }
1369
1370 #[inline(always)]
1375 #[must_use]
1376 #[cfg(feature = "latest_stable_rust")]
1377 pub const fn as_mut_inner(&mut self) -> &mut A {
1378 &mut self.data
1379 }
1380}
1381
1382pub struct ArrayVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> {
1385 parent: &'p mut ArrayVec<A>,
1386 removal_start: usize,
1387 removal_end: usize,
1388 replacement: I,
1389}
1390
1391impl<'p, A: Array, I: Iterator<Item = A::Item>> Iterator
1392 for ArrayVecSplice<'p, A, I>
1393{
1394 type Item = A::Item;
1395
1396 #[inline]
1397 fn next(&mut self) -> Option<A::Item> {
1398 if self.removal_start < self.removal_end {
1399 match self.replacement.next() {
1400 Some(replacement) => {
1401 let removed = core::mem::replace(
1402 &mut self.parent[self.removal_start],
1403 replacement,
1404 );
1405 self.removal_start += 1;
1406 Some(removed)
1407 }
1408 None => {
1409 let removed = self.parent.remove(self.removal_start);
1410 self.removal_end -= 1;
1411 Some(removed)
1412 }
1413 }
1414 } else {
1415 None
1416 }
1417 }
1418
1419 #[inline]
1420 fn size_hint(&self) -> (usize, Option<usize>) {
1421 let len = self.len();
1422 (len, Some(len))
1423 }
1424}
1425
1426impl<'p, A, I> ExactSizeIterator for ArrayVecSplice<'p, A, I>
1427where
1428 A: Array,
1429 I: Iterator<Item = A::Item>,
1430{
1431 #[inline]
1432 fn len(&self) -> usize {
1433 self.removal_end - self.removal_start
1434 }
1435}
1436
1437impl<'p, A, I> FusedIterator for ArrayVecSplice<'p, A, I>
1438where
1439 A: Array,
1440 I: Iterator<Item = A::Item>,
1441{
1442}
1443
1444impl<'p, A, I> DoubleEndedIterator for ArrayVecSplice<'p, A, I>
1445where
1446 A: Array,
1447 I: Iterator<Item = A::Item> + DoubleEndedIterator,
1448{
1449 #[inline]
1450 fn next_back(&mut self) -> Option<A::Item> {
1451 if self.removal_start < self.removal_end {
1452 match self.replacement.next_back() {
1453 Some(replacement) => {
1454 let removed = core::mem::replace(
1455 &mut self.parent[self.removal_end - 1],
1456 replacement,
1457 );
1458 self.removal_end -= 1;
1459 Some(removed)
1460 }
1461 None => {
1462 let removed = self.parent.remove(self.removal_end - 1);
1463 self.removal_end -= 1;
1464 Some(removed)
1465 }
1466 }
1467 } else {
1468 None
1469 }
1470 }
1471}
1472
1473impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop
1474 for ArrayVecSplice<'p, A, I>
1475{
1476 #[inline]
1477 fn drop(&mut self) {
1478 for _ in self.by_ref() {}
1479
1480 for replacement in self.replacement.by_ref() {
1483 self.parent.insert(self.removal_end, replacement);
1484 self.removal_end += 1;
1485 }
1486 }
1487}
1488
1489impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> {
1490 #[inline(always)]
1491 fn as_mut(&mut self) -> &mut [A::Item] {
1492 &mut *self
1493 }
1494}
1495
1496impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> {
1497 #[inline(always)]
1498 fn as_ref(&self) -> &[A::Item] {
1499 &*self
1500 }
1501}
1502
1503impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> {
1504 #[inline(always)]
1505 fn borrow(&self) -> &[A::Item] {
1506 &*self
1507 }
1508}
1509
1510impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> {
1511 #[inline(always)]
1512 fn borrow_mut(&mut self) -> &mut [A::Item] {
1513 &mut *self
1514 }
1515}
1516
1517impl<A: Array> Extend<A::Item> for ArrayVec<A> {
1518 #[inline]
1519 fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) {
1520 for t in iter {
1521 self.push(t)
1522 }
1523 }
1524}
1525
1526impl<A: Array> From<A> for ArrayVec<A> {
1527 #[inline(always)]
1528 fn from(data: A) -> Self {
1533 let len: u16 = data
1534 .as_slice()
1535 .len()
1536 .try_into()
1537 .expect("ArrayVec::from> length must be in range 0..=u16::MAX");
1538 Self { len, data }
1539 }
1540}
1541
1542#[derive(Debug, Copy, Clone)]
1545#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1546pub struct TryFromSliceError(());
1547
1548impl core::fmt::Display for TryFromSliceError {
1549 #[inline]
1550 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1551 f.write_str("could not convert slice to ArrayVec")
1552 }
1553}
1554
1555#[cfg(feature = "std")]
1556impl std::error::Error for TryFromSliceError {}
1557
1558impl<T, A> TryFrom<&'_ [T]> for ArrayVec<A>
1559where
1560 T: Clone + Default,
1561 A: Array<Item = T>,
1562{
1563 type Error = TryFromSliceError;
1564
1565 #[inline]
1566 fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
1569 if slice.len() > A::CAPACITY {
1570 Err(TryFromSliceError(()))
1571 } else {
1572 let mut arr = ArrayVec::new();
1573 arr.set_len(slice.len());
1581 arr.as_mut_slice().clone_from_slice(slice);
1582 Ok(arr)
1583 }
1584 }
1585}
1586
1587impl<A: Array> FromIterator<A::Item> for ArrayVec<A> {
1588 #[inline]
1589 fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self {
1590 let mut av = Self::default();
1591 for i in iter {
1592 av.push(i)
1593 }
1594 av
1595 }
1596}
1597
1598pub struct ArrayVecIterator<A: Array> {
1600 base: u16,
1601 tail: u16,
1602 data: A,
1603}
1604
1605impl<A: Array> ArrayVecIterator<A> {
1606 #[inline]
1608 #[must_use]
1609 pub fn as_slice(&self) -> &[A::Item] {
1610 &self.data.as_slice()[self.base as usize..self.tail as usize]
1611 }
1612}
1613impl<A: Array> FusedIterator for ArrayVecIterator<A> {}
1614impl<A: Array> Iterator for ArrayVecIterator<A> {
1615 type Item = A::Item;
1616 #[inline]
1617 fn next(&mut self) -> Option<Self::Item> {
1618 let slice =
1619 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1620 let itemref = slice.first_mut()?;
1621 self.base += 1;
1622 return Some(core::mem::take(itemref));
1623 }
1624 #[inline(always)]
1625 fn size_hint(&self) -> (usize, Option<usize>) {
1626 let s = self.tail - self.base;
1627 let s = s as usize;
1628 (s, Some(s))
1629 }
1630 #[inline(always)]
1631 fn count(self) -> usize {
1632 self.size_hint().0
1633 }
1634 #[inline]
1635 fn last(mut self) -> Option<Self::Item> {
1636 self.next_back()
1637 }
1638 #[inline]
1639 fn nth(&mut self, n: usize) -> Option<A::Item> {
1640 let slice = &mut self.data.as_slice_mut();
1641 let slice = &mut slice[self.base as usize..self.tail as usize];
1642
1643 if let Some(x) = slice.get_mut(n) {
1644 self.base += n as u16 + 1;
1646 return Some(core::mem::take(x));
1647 }
1648
1649 self.base = self.tail;
1650 return None;
1651 }
1652}
1653
1654impl<A: Array> DoubleEndedIterator for ArrayVecIterator<A> {
1655 #[inline]
1656 fn next_back(&mut self) -> Option<Self::Item> {
1657 let slice =
1658 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1659 let item = slice.last_mut()?;
1660 self.tail -= 1;
1661 return Some(core::mem::take(item));
1662 }
1663
1664 #[inline]
1665 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1666 let base = self.base as usize;
1667 let tail = self.tail as usize;
1668 let slice = &mut self.data.as_slice_mut()[base..tail];
1669 let n = n.saturating_add(1);
1670
1671 if let Some(n) = slice.len().checked_sub(n) {
1672 let item = &mut slice[n];
1673 self.tail = self.base + n as u16;
1675 return Some(core::mem::take(item));
1676 }
1677
1678 self.tail = self.base;
1679 return None;
1680 }
1681}
1682
1683impl<A: Array> ExactSizeIterator for ArrayVecIterator<A> {
1684 #[inline]
1685 fn len(&self) -> usize {
1686 self.size_hint().0
1687 }
1688}
1689
1690impl<A: Array> Debug for ArrayVecIterator<A>
1691where
1692 A::Item: Debug,
1693{
1694 #[allow(clippy::missing_inline_in_public_items)]
1695 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1696 f.debug_tuple("ArrayVecIterator").field(&self.as_slice()).finish()
1697 }
1698}
1699
1700#[cfg(feature = "defmt")]
1701#[cfg_attr(docs_rs, doc(cfg(feature = "defmt")))]
1702impl<A: Array> defmt::Format for ArrayVecIterator<A>
1703where
1704 A::Item: defmt::Format,
1705{
1706 fn format(&self, fmt: defmt::Formatter<'_>) {
1707 defmt::write!(fmt, "ArrayVecIterator({:?})", self.as_slice())
1708 }
1709}
1710
1711impl<A: Array> IntoIterator for ArrayVec<A> {
1712 type Item = A::Item;
1713 type IntoIter = ArrayVecIterator<A>;
1714 #[inline(always)]
1715 fn into_iter(self) -> Self::IntoIter {
1716 ArrayVecIterator { base: 0, tail: self.len, data: self.data }
1717 }
1718}
1719
1720impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
1721 type Item = &'a mut A::Item;
1722 type IntoIter = core::slice::IterMut<'a, A::Item>;
1723 #[inline(always)]
1724 fn into_iter(self) -> Self::IntoIter {
1725 self.iter_mut()
1726 }
1727}
1728
1729impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
1730 type Item = &'a A::Item;
1731 type IntoIter = core::slice::Iter<'a, A::Item>;
1732 #[inline(always)]
1733 fn into_iter(self) -> Self::IntoIter {
1734 self.iter()
1735 }
1736}
1737
1738impl<A: Array> PartialEq for ArrayVec<A>
1739where
1740 A::Item: PartialEq,
1741{
1742 #[inline]
1743 fn eq(&self, other: &Self) -> bool {
1744 self.as_slice().eq(other.as_slice())
1745 }
1746}
1747impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq {}
1748
1749impl<A: Array> PartialOrd for ArrayVec<A>
1750where
1751 A::Item: PartialOrd,
1752{
1753 #[inline]
1754 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1755 self.as_slice().partial_cmp(other.as_slice())
1756 }
1757}
1758impl<A: Array> Ord for ArrayVec<A>
1759where
1760 A::Item: Ord,
1761{
1762 #[inline]
1763 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1764 self.as_slice().cmp(other.as_slice())
1765 }
1766}
1767
1768impl<A: Array> PartialEq<&A> for ArrayVec<A>
1769where
1770 A::Item: PartialEq,
1771{
1772 #[inline]
1773 fn eq(&self, other: &&A) -> bool {
1774 self.as_slice().eq(other.as_slice())
1775 }
1776}
1777
1778impl<A: Array> PartialEq<&[A::Item]> for ArrayVec<A>
1779where
1780 A::Item: PartialEq,
1781{
1782 #[inline]
1783 fn eq(&self, other: &&[A::Item]) -> bool {
1784 self.as_slice().eq(*other)
1785 }
1786}
1787
1788impl<A: Array> Hash for ArrayVec<A>
1789where
1790 A::Item: Hash,
1791{
1792 #[inline]
1793 fn hash<H: Hasher>(&self, state: &mut H) {
1794 self.as_slice().hash(state)
1795 }
1796}
1797
1798#[cfg(feature = "experimental_write_impl")]
1799impl<A: Array<Item = u8>> core::fmt::Write for ArrayVec<A> {
1800 fn write_str(&mut self, s: &str) -> core::fmt::Result {
1801 let my_len = self.len();
1802 let str_len = s.as_bytes().len();
1803 if my_len + str_len <= A::CAPACITY {
1804 let remainder = &mut self.data.as_slice_mut()[my_len..];
1805 let target = &mut remainder[..str_len];
1806 target.copy_from_slice(s.as_bytes());
1807 Ok(())
1808 } else {
1809 Err(core::fmt::Error)
1810 }
1811 }
1812}
1813
1814impl<A: Array> Binary for ArrayVec<A>
1819where
1820 A::Item: Binary,
1821{
1822 #[allow(clippy::missing_inline_in_public_items)]
1823 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1824 write!(f, "[")?;
1825 if f.alternate() {
1826 write!(f, "\n ")?;
1827 }
1828 for (i, elem) in self.iter().enumerate() {
1829 if i > 0 {
1830 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1831 }
1832 Binary::fmt(elem, f)?;
1833 }
1834 if f.alternate() {
1835 write!(f, ",\n")?;
1836 }
1837 write!(f, "]")
1838 }
1839}
1840
1841impl<A: Array> Debug for ArrayVec<A>
1842where
1843 A::Item: Debug,
1844{
1845 #[allow(clippy::missing_inline_in_public_items)]
1846 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1847 <[A::Item] as Debug>::fmt(self.as_slice(), f)
1848 }
1849}
1850
1851#[cfg(feature = "defmt")]
1852#[cfg_attr(docs_rs, doc(cfg(feature = "defmt")))]
1853impl<A: Array> defmt::Format for ArrayVec<A>
1854where
1855 A::Item: defmt::Format,
1856{
1857 fn format(&self, fmt: defmt::Formatter<'_>) {
1858 defmt::Format::format(self.as_slice(), fmt)
1859 }
1860}
1861
1862impl<A: Array> Display for ArrayVec<A>
1863where
1864 A::Item: Display,
1865{
1866 #[allow(clippy::missing_inline_in_public_items)]
1867 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1868 write!(f, "[")?;
1869 if f.alternate() {
1870 write!(f, "\n ")?;
1871 }
1872 for (i, elem) in self.iter().enumerate() {
1873 if i > 0 {
1874 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1875 }
1876 Display::fmt(elem, f)?;
1877 }
1878 if f.alternate() {
1879 write!(f, ",\n")?;
1880 }
1881 write!(f, "]")
1882 }
1883}
1884
1885impl<A: Array> LowerExp for ArrayVec<A>
1886where
1887 A::Item: LowerExp,
1888{
1889 #[allow(clippy::missing_inline_in_public_items)]
1890 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1891 write!(f, "[")?;
1892 if f.alternate() {
1893 write!(f, "\n ")?;
1894 }
1895 for (i, elem) in self.iter().enumerate() {
1896 if i > 0 {
1897 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1898 }
1899 LowerExp::fmt(elem, f)?;
1900 }
1901 if f.alternate() {
1902 write!(f, ",\n")?;
1903 }
1904 write!(f, "]")
1905 }
1906}
1907
1908impl<A: Array> LowerHex for ArrayVec<A>
1909where
1910 A::Item: LowerHex,
1911{
1912 #[allow(clippy::missing_inline_in_public_items)]
1913 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1914 write!(f, "[")?;
1915 if f.alternate() {
1916 write!(f, "\n ")?;
1917 }
1918 for (i, elem) in self.iter().enumerate() {
1919 if i > 0 {
1920 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1921 }
1922 LowerHex::fmt(elem, f)?;
1923 }
1924 if f.alternate() {
1925 write!(f, ",\n")?;
1926 }
1927 write!(f, "]")
1928 }
1929}
1930
1931impl<A: Array> Octal for ArrayVec<A>
1932where
1933 A::Item: Octal,
1934{
1935 #[allow(clippy::missing_inline_in_public_items)]
1936 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1937 write!(f, "[")?;
1938 if f.alternate() {
1939 write!(f, "\n ")?;
1940 }
1941 for (i, elem) in self.iter().enumerate() {
1942 if i > 0 {
1943 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1944 }
1945 Octal::fmt(elem, f)?;
1946 }
1947 if f.alternate() {
1948 write!(f, ",\n")?;
1949 }
1950 write!(f, "]")
1951 }
1952}
1953
1954impl<A: Array> Pointer for ArrayVec<A>
1955where
1956 A::Item: Pointer,
1957{
1958 #[allow(clippy::missing_inline_in_public_items)]
1959 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1960 write!(f, "[")?;
1961 if f.alternate() {
1962 write!(f, "\n ")?;
1963 }
1964 for (i, elem) in self.iter().enumerate() {
1965 if i > 0 {
1966 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1967 }
1968 Pointer::fmt(elem, f)?;
1969 }
1970 if f.alternate() {
1971 write!(f, ",\n")?;
1972 }
1973 write!(f, "]")
1974 }
1975}
1976
1977impl<A: Array> UpperExp for ArrayVec<A>
1978where
1979 A::Item: UpperExp,
1980{
1981 #[allow(clippy::missing_inline_in_public_items)]
1982 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1983 write!(f, "[")?;
1984 if f.alternate() {
1985 write!(f, "\n ")?;
1986 }
1987 for (i, elem) in self.iter().enumerate() {
1988 if i > 0 {
1989 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1990 }
1991 UpperExp::fmt(elem, f)?;
1992 }
1993 if f.alternate() {
1994 write!(f, ",\n")?;
1995 }
1996 write!(f, "]")
1997 }
1998}
1999
2000impl<A: Array> UpperHex for ArrayVec<A>
2001where
2002 A::Item: UpperHex,
2003{
2004 #[allow(clippy::missing_inline_in_public_items)]
2005 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
2006 write!(f, "[")?;
2007 if f.alternate() {
2008 write!(f, "\n ")?;
2009 }
2010 for (i, elem) in self.iter().enumerate() {
2011 if i > 0 {
2012 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
2013 }
2014 UpperHex::fmt(elem, f)?;
2015 }
2016 if f.alternate() {
2017 write!(f, ",\n")?;
2018 }
2019 write!(f, "]")
2020 }
2021}
2022
2023#[cfg(feature = "alloc")]
2024use alloc::vec::Vec;
2025
2026#[cfg(all(feature = "alloc", feature = "rustc_1_57"))]
2027use alloc::collections::TryReserveError;
2028
2029#[cfg(feature = "alloc")]
2030impl<A: Array> ArrayVec<A> {
2031 #[inline]
2040 pub fn drain_to_vec_and_reserve(&mut self, n: usize) -> Vec<A::Item> {
2041 let cap = n + self.len();
2042 let mut v = Vec::with_capacity(cap);
2043 let iter = self.iter_mut().map(core::mem::take);
2044 v.extend(iter);
2045 self.set_len(0);
2046 return v;
2047 }
2048
2049 #[inline]
2065 #[cfg(feature = "rustc_1_57")]
2066 pub fn try_drain_to_vec_and_reserve(
2067 &mut self, n: usize,
2068 ) -> Result<Vec<A::Item>, TryReserveError> {
2069 let cap = n + self.len();
2070 let mut v = Vec::new();
2071 v.try_reserve(cap)?;
2072 let iter = self.iter_mut().map(core::mem::take);
2073 v.extend(iter);
2074 self.set_len(0);
2075 return Ok(v);
2076 }
2077
2078 #[inline]
2087 pub fn drain_to_vec(&mut self) -> Vec<A::Item> {
2088 self.drain_to_vec_and_reserve(0)
2089 }
2090
2091 #[inline]
2108 #[cfg(feature = "rustc_1_57")]
2109 pub fn try_drain_to_vec(&mut self) -> Result<Vec<A::Item>, TryReserveError> {
2110 self.try_drain_to_vec_and_reserve(0)
2111 }
2112}
2113
2114#[cfg(feature = "serde")]
2115struct ArrayVecVisitor<A: Array>(PhantomData<A>);
2116
2117#[cfg(feature = "serde")]
2118impl<'de, A: Array> Visitor<'de> for ArrayVecVisitor<A>
2119where
2120 A::Item: Deserialize<'de>,
2121{
2122 type Value = ArrayVec<A>;
2123
2124 fn expecting(
2125 &self, formatter: &mut core::fmt::Formatter,
2126 ) -> core::fmt::Result {
2127 formatter.write_str("a sequence")
2128 }
2129
2130 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
2131 where
2132 S: SeqAccess<'de>,
2133 {
2134 let mut new_arrayvec: ArrayVec<A> = Default::default();
2135
2136 let mut idx = 0usize;
2137 while let Some(value) = seq.next_element()? {
2138 if new_arrayvec.len() >= new_arrayvec.capacity() {
2139 return Err(DeserializeError::invalid_length(idx, &self));
2140 }
2141 new_arrayvec.push(value);
2142 idx = idx + 1;
2143 }
2144
2145 Ok(new_arrayvec)
2146 }
2147}
2148
2149#[cfg(test)]
2150mod test {
2151 use super::*;
2152
2153 #[test]
2154 fn retain_mut_empty_vec() {
2155 let mut av: ArrayVec<[i32; 4]> = ArrayVec::new();
2156 av.retain_mut(|&mut x| x % 2 == 0);
2157 assert_eq!(av.len(), 0);
2158 }
2159
2160 #[test]
2161 fn retain_mut_all_elements() {
2162 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 2, 4, 6, 8);
2163 av.retain_mut(|&mut x| x % 2 == 0);
2164 assert_eq!(av.len(), 4);
2165 assert_eq!(av.as_slice(), &[2, 4, 6, 8]);
2166 }
2167
2168 #[test]
2169 fn retain_mut_some_elements() {
2170 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 2, 3, 4);
2171 av.retain_mut(|&mut x| x % 2 == 0);
2172 assert_eq!(av.len(), 2);
2173 assert_eq!(av.as_slice(), &[2, 4]);
2174 }
2175
2176 #[test]
2177 fn retain_mut_no_elements() {
2178 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 3, 5, 7);
2179 av.retain_mut(|&mut x| x % 2 == 0);
2180 assert_eq!(av.len(), 0);
2181 }
2182
2183 #[test]
2184 fn retain_mut_zero_capacity() {
2185 let mut av: ArrayVec<[i32; 0]> = ArrayVec::new();
2186 av.retain_mut(|&mut x| x % 2 == 0);
2187 assert_eq!(av.len(), 0);
2188 }
2189
2190 #[cfg(feature = "alloc")]
2191 #[test]
2192 fn array_like_debug() {
2193 #[derive(Debug, Default, Copy, Clone)]
2194 struct S {
2195 x: u8,
2196 y: u8,
2197 }
2198
2199 use core::fmt::Write;
2200
2201 let mut ar: [S; 2] = [S { x: 1, y: 2 }, S { x: 3, y: 4 }];
2202 let mut buf_ar = alloc::string::String::new();
2203 write!(&mut buf_ar, "{ar:#?}");
2204
2205 let av: ArrayVec<[S; 2]> = ArrayVec::from(ar);
2206 let mut buf_av = alloc::string::String::new();
2207 write!(&mut buf_av, "{av:#?}");
2208
2209 assert_eq!(buf_av, buf_ar)
2210 }
2211}