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
290impl<A: Array> ArrayVec<A> {
291 #[inline]
306 pub fn append(&mut self, other: &mut Self) {
307 assert!(
308 self.try_append(other).is_none(),
309 "ArrayVec::append> total length {} exceeds capacity {}!",
310 self.len() + other.len(),
311 A::CAPACITY
312 );
313 }
314
315 #[inline]
332 pub fn try_append<'other>(
333 &mut self, other: &'other mut Self,
334 ) -> Option<&'other mut Self> {
335 let new_len = self.len() + other.len();
336 if new_len > A::CAPACITY {
337 return Some(other);
338 }
339
340 let iter = other.iter_mut().map(core::mem::take);
341 for item in iter {
342 self.push(item);
343 }
344
345 other.set_len(0);
346
347 return None;
348 }
349
350 #[inline(always)]
356 #[must_use]
357 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
358 self.data.as_slice_mut().as_mut_ptr()
359 }
360
361 #[inline(always)]
363 #[must_use]
364 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
365 self.deref_mut()
366 }
367
368 #[inline(always)]
374 #[must_use]
375 pub fn as_ptr(&self) -> *const A::Item {
376 self.data.as_slice().as_ptr()
377 }
378
379 #[inline(always)]
381 #[must_use]
382 pub fn as_slice(&self) -> &[A::Item] {
383 self.deref()
384 }
385
386 #[inline(always)]
391 #[must_use]
392 pub fn capacity(&self) -> usize {
393 self.data.as_slice().len().min(u16::MAX as usize)
397 }
398
399 #[inline(always)]
401 pub fn clear(&mut self) {
402 self.truncate(0)
403 }
404
405 #[inline]
424 pub fn drain<R>(&mut self, range: R) -> ArrayVecDrain<'_, A::Item>
425 where
426 R: RangeBounds<usize>,
427 {
428 ArrayVecDrain::new(self, range)
429 }
430
431 #[inline]
457 pub fn into_inner(self) -> A {
458 self.data
459 }
460
461 #[inline]
466 pub fn extend_from_slice(&mut self, sli: &[A::Item])
467 where
468 A::Item: Clone,
469 {
470 if sli.is_empty() {
471 return;
472 }
473
474 let new_len = self.len as usize + sli.len();
475 assert!(
476 new_len <= A::CAPACITY,
477 "ArrayVec::extend_from_slice> total length {} exceeds capacity {}!",
478 new_len,
479 A::CAPACITY
480 );
481
482 let target = &mut self.data.as_slice_mut()[self.len as usize..new_len];
483 target.clone_from_slice(sli);
484 self.set_len(new_len);
485 }
486
487 #[inline]
513 pub fn fill<I: IntoIterator<Item = A::Item>>(
514 &mut self, iter: I,
515 ) -> I::IntoIter {
516 let mut iter = iter.into_iter();
521 let mut pushed = 0;
522 let to_take = self.capacity() - self.len();
523 let target = &mut self.data.as_slice_mut()[self.len as usize..];
524 for element in iter.by_ref().take(to_take) {
525 target[pushed] = element;
526 pushed += 1;
527 }
528 self.len += pushed as u16;
529 iter
530 }
531
532 #[inline]
541 #[must_use]
542 #[allow(clippy::match_wild_err_arm)]
543 pub fn from_array_len(data: A, len: usize) -> Self {
544 match Self::try_from_array_len(data, len) {
545 Ok(out) => out,
546 Err(_) => panic!(
547 "ArrayVec::from_array_len> length {} exceeds capacity {}!",
548 len,
549 A::CAPACITY
550 ),
551 }
552 }
553
554 #[inline]
571 pub fn insert(&mut self, index: usize, item: A::Item) {
572 let x = self.try_insert(index, item);
573 assert!(x.is_none(), "ArrayVec::insert> capacity overflow!");
574 }
575
576 #[inline]
593 pub fn try_insert(
594 &mut self, index: usize, mut item: A::Item,
595 ) -> Option<A::Item> {
596 assert!(
597 index <= self.len as usize,
598 "ArrayVec::try_insert> index {} is out of bounds {}",
599 index,
600 self.len
601 );
602
603 if (self.len as usize) < A::CAPACITY {
611 self.len += 1;
612 } else {
613 return Some(item);
614 }
615
616 let target = &mut self.as_mut_slice()[index..];
617 #[allow(clippy::needless_range_loop)]
618 for i in 0..target.len() {
619 core::mem::swap(&mut item, &mut target[i]);
620 }
621 return None;
622 }
623
624 #[inline(always)]
626 #[must_use]
627 pub fn is_empty(&self) -> bool {
628 self.len == 0
629 }
630
631 #[inline(always)]
633 #[must_use]
634 pub fn is_full(&self) -> bool {
635 self.len() == self.capacity()
636 }
637
638 #[inline(always)]
640 #[must_use]
641 pub fn len(&self) -> usize {
642 self.len as usize
643 }
644
645 #[inline(always)]
647 #[must_use]
648 pub fn new() -> Self {
649 Self::default()
650 }
651
652 #[inline]
666 pub fn pop(&mut self) -> Option<A::Item> {
667 if self.len > 0 {
668 self.len -= 1;
669 let out =
670 core::mem::take(&mut self.data.as_slice_mut()[self.len as usize]);
671 Some(out)
672 } else {
673 None
674 }
675 }
676
677 #[inline(always)]
694 pub fn push(&mut self, val: A::Item) {
695 let x = self.try_push(val);
696 assert!(x.is_none(), "ArrayVec::push> capacity overflow!");
697 }
698
699 #[inline(always)]
713 pub fn try_push(&mut self, val: A::Item) -> Option<A::Item> {
714 debug_assert!(self.len as usize <= A::CAPACITY);
715
716 let itemref = match self.data.as_slice_mut().get_mut(self.len as usize) {
717 None => return Some(val),
718 Some(x) => x,
719 };
720
721 *itemref = val;
722 self.len += 1;
723 return None;
724 }
725
726 #[inline]
743 pub fn remove(&mut self, index: usize) -> A::Item {
744 let targets: &mut [A::Item] = &mut self.deref_mut()[index..];
745 let item = core::mem::take(&mut targets[0]);
746
747 for i in 0..targets.len() - 1 {
755 targets.swap(i, i + 1);
756 }
757 self.len -= 1;
758 item
759 }
760
761 #[inline]
778 pub fn resize(&mut self, new_len: usize, new_val: A::Item)
779 where
780 A::Item: Clone,
781 {
782 self.resize_with(new_len, || new_val.clone())
783 }
784
785 #[inline]
808 pub fn resize_with<F: FnMut() -> A::Item>(
809 &mut self, new_len: usize, mut f: F,
810 ) {
811 match new_len.checked_sub(self.len as usize) {
812 None => self.truncate(new_len),
813 Some(new_elements) => {
814 for _ in 0..new_elements {
815 self.push(f());
816 }
817 }
818 }
819 }
820
821 #[inline]
833 pub fn retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F) {
834 struct JoinOnDrop<'vec, Item> {
837 items: &'vec mut [Item],
838 done_end: usize,
839 tail_start: usize,
841 }
842
843 impl<Item> Drop for JoinOnDrop<'_, Item> {
844 fn drop(&mut self) {
845 self.items[self.done_end..].rotate_left(self.tail_start);
846 }
847 }
848
849 let mut rest = JoinOnDrop {
850 items: &mut self.data.as_slice_mut()[..self.len as usize],
851 done_end: 0,
852 tail_start: 0,
853 };
854
855 let len = self.len as usize;
856 for idx in 0..len {
857 if !acceptable(&rest.items[idx]) {
859 let _ = core::mem::take(&mut rest.items[idx]);
860 self.len -= 1;
861 rest.tail_start += 1;
862 } else {
863 rest.items.swap(rest.done_end, idx);
864 rest.done_end += 1;
865 }
866 }
867 }
868
869 #[inline]
887 pub fn retain_mut<F>(&mut self, mut acceptable: F)
888 where
889 F: FnMut(&mut A::Item) -> bool,
890 {
891 struct JoinOnDrop<'vec, Item> {
894 items: &'vec mut [Item],
895 done_end: usize,
896 tail_start: usize,
898 }
899
900 impl<Item> Drop for JoinOnDrop<'_, Item> {
901 fn drop(&mut self) {
902 self.items[self.done_end..].rotate_left(self.tail_start);
903 }
904 }
905
906 let mut rest = JoinOnDrop {
907 items: &mut self.data.as_slice_mut()[..self.len as usize],
908 done_end: 0,
909 tail_start: 0,
910 };
911
912 let len = self.len as usize;
913 for idx in 0..len {
914 if !acceptable(&mut rest.items[idx]) {
916 let _ = core::mem::take(&mut rest.items[idx]);
917 self.len -= 1;
918 rest.tail_start += 1;
919 } else {
920 rest.items.swap(rest.done_end, idx);
921 rest.done_end += 1;
922 }
923 }
924 }
925
926 #[inline(always)]
937 pub fn set_len(&mut self, new_len: usize) {
938 if new_len > A::CAPACITY {
939 panic!(
944 "ArrayVec::set_len> new length {} exceeds capacity {}",
945 new_len,
946 A::CAPACITY
947 )
948 }
949
950 let new_len: u16 = new_len
951 .try_into()
952 .expect("ArrayVec::set_len> new length is not in range 0..=u16::MAX");
953 self.len = new_len;
954 }
955
956 #[inline]
974 pub fn split_off(&mut self, at: usize) -> Self {
975 if at > self.len() {
977 panic!(
978 "ArrayVec::split_off> at value {} exceeds length of {}",
979 at, self.len
980 );
981 }
982 let mut new = Self::default();
983 let moves = &mut self.as_mut_slice()[at..];
984 let split_len = moves.len();
985 let targets = &mut new.data.as_slice_mut()[..split_len];
986 moves.swap_with_slice(targets);
987
988 new.len = split_len as u16;
990 self.len = at as u16;
991 new
992 }
993
994 #[inline]
1021 pub fn splice<R, I>(
1022 &mut self, range: R, replacement: I,
1023 ) -> ArrayVecSplice<'_, A, core::iter::Fuse<I::IntoIter>>
1024 where
1025 R: RangeBounds<usize>,
1026 I: IntoIterator<Item = A::Item>,
1027 {
1028 use core::ops::Bound;
1029 let start = match range.start_bound() {
1030 Bound::Included(x) => *x,
1031 Bound::Excluded(x) => x.saturating_add(1),
1032 Bound::Unbounded => 0,
1033 };
1034 let end = match range.end_bound() {
1035 Bound::Included(x) => x.saturating_add(1),
1036 Bound::Excluded(x) => *x,
1037 Bound::Unbounded => self.len(),
1038 };
1039 assert!(
1040 start <= end,
1041 "ArrayVec::splice> Illegal range, {} to {}",
1042 start,
1043 end
1044 );
1045 assert!(
1046 end <= self.len(),
1047 "ArrayVec::splice> Range ends at {} but length is only {}!",
1048 end,
1049 self.len()
1050 );
1051
1052 ArrayVecSplice {
1053 removal_start: start,
1054 removal_end: end,
1055 parent: self,
1056 replacement: replacement.into_iter().fuse(),
1057 }
1058 }
1059
1060 #[inline]
1077 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1078 assert!(
1079 index < self.len(),
1080 "ArrayVec::swap_remove> index {} is out of bounds {}",
1081 index,
1082 self.len
1083 );
1084 if index == self.len() - 1 {
1085 self.pop().unwrap()
1086 } else {
1087 let i = self.pop().unwrap();
1088 replace(&mut self[index], i)
1089 }
1090 }
1091
1092 #[inline]
1096 pub fn truncate(&mut self, new_len: usize) {
1097 if new_len >= self.len as usize {
1098 return;
1099 }
1100
1101 if needs_drop::<A::Item>() {
1102 let len = self.len as usize;
1103 self.data.as_slice_mut()[new_len..len]
1104 .iter_mut()
1105 .map(core::mem::take)
1106 .for_each(drop);
1107 }
1108
1109 self.len = new_len as u16;
1111 }
1112
1113 #[inline]
1123 #[cfg(not(feature = "latest_stable_rust"))]
1124 pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1125 if len <= A::CAPACITY {
1127 Ok(Self { data, len: len as u16 })
1128 } else {
1129 Err(data)
1130 }
1131 }
1132
1133 #[inline]
1143 #[cfg(feature = "latest_stable_rust")]
1144 pub const fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1145 if len <= A::CAPACITY {
1147 Ok(Self { data, len: len as u16 })
1148 } else {
1149 Err(data)
1150 }
1151 }
1152}
1153
1154impl<A> ArrayVec<A> {
1155 #[inline]
1179 #[must_use]
1180 pub const fn from_array_empty(data: A) -> Self {
1181 Self { data, len: 0 }
1182 }
1183}
1184
1185#[cfg(feature = "grab_spare_slice")]
1186impl<A: Array> ArrayVec<A> {
1187 #[inline(always)]
1201 pub fn grab_spare_slice(&self) -> &[A::Item] {
1202 &self.data.as_slice()[self.len as usize..]
1203 }
1204
1205 #[inline(always)]
1217 pub fn grab_spare_slice_mut(&mut self) -> &mut [A::Item] {
1218 &mut self.data.as_slice_mut()[self.len as usize..]
1219 }
1220}
1221
1222#[cfg(feature = "nightly_slice_partition_dedup")]
1223impl<A: Array> ArrayVec<A> {
1224 #[inline(always)]
1226 pub fn dedup(&mut self)
1227 where
1228 A::Item: PartialEq,
1229 {
1230 self.dedup_by(|a, b| a == b)
1231 }
1232
1233 #[inline(always)]
1235 pub fn dedup_by<F>(&mut self, same_bucket: F)
1236 where
1237 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1238 {
1239 let len = {
1240 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1241 dedup.len()
1242 };
1243 self.truncate(len);
1244 }
1245
1246 #[inline(always)]
1248 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1249 where
1250 F: FnMut(&mut A::Item) -> K,
1251 K: PartialEq,
1252 {
1253 self.dedup_by(|a, b| key(a) == key(b))
1254 }
1255}
1256
1257impl<A> ArrayVec<A> {
1258 #[inline(always)]
1263 #[must_use]
1264 pub const fn as_inner(&self) -> &A {
1265 &self.data
1266 }
1267
1268 #[inline(always)]
1273 #[must_use]
1274 #[cfg(feature = "latest_stable_rust")]
1275 pub const fn as_mut_inner(&mut self) -> &mut A {
1276 &mut self.data
1277 }
1278}
1279
1280pub struct ArrayVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> {
1283 parent: &'p mut ArrayVec<A>,
1284 removal_start: usize,
1285 removal_end: usize,
1286 replacement: I,
1287}
1288
1289impl<'p, A: Array, I: Iterator<Item = A::Item>> Iterator
1290 for ArrayVecSplice<'p, A, I>
1291{
1292 type Item = A::Item;
1293
1294 #[inline]
1295 fn next(&mut self) -> Option<A::Item> {
1296 if self.removal_start < self.removal_end {
1297 match self.replacement.next() {
1298 Some(replacement) => {
1299 let removed = core::mem::replace(
1300 &mut self.parent[self.removal_start],
1301 replacement,
1302 );
1303 self.removal_start += 1;
1304 Some(removed)
1305 }
1306 None => {
1307 let removed = self.parent.remove(self.removal_start);
1308 self.removal_end -= 1;
1309 Some(removed)
1310 }
1311 }
1312 } else {
1313 None
1314 }
1315 }
1316
1317 #[inline]
1318 fn size_hint(&self) -> (usize, Option<usize>) {
1319 let len = self.len();
1320 (len, Some(len))
1321 }
1322}
1323
1324impl<'p, A, I> ExactSizeIterator for ArrayVecSplice<'p, A, I>
1325where
1326 A: Array,
1327 I: Iterator<Item = A::Item>,
1328{
1329 #[inline]
1330 fn len(&self) -> usize {
1331 self.removal_end - self.removal_start
1332 }
1333}
1334
1335impl<'p, A, I> FusedIterator for ArrayVecSplice<'p, A, I>
1336where
1337 A: Array,
1338 I: Iterator<Item = A::Item>,
1339{
1340}
1341
1342impl<'p, A, I> DoubleEndedIterator for ArrayVecSplice<'p, A, I>
1343where
1344 A: Array,
1345 I: Iterator<Item = A::Item> + DoubleEndedIterator,
1346{
1347 #[inline]
1348 fn next_back(&mut self) -> Option<A::Item> {
1349 if self.removal_start < self.removal_end {
1350 match self.replacement.next_back() {
1351 Some(replacement) => {
1352 let removed = core::mem::replace(
1353 &mut self.parent[self.removal_end - 1],
1354 replacement,
1355 );
1356 self.removal_end -= 1;
1357 Some(removed)
1358 }
1359 None => {
1360 let removed = self.parent.remove(self.removal_end - 1);
1361 self.removal_end -= 1;
1362 Some(removed)
1363 }
1364 }
1365 } else {
1366 None
1367 }
1368 }
1369}
1370
1371impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop
1372 for ArrayVecSplice<'p, A, I>
1373{
1374 #[inline]
1375 fn drop(&mut self) {
1376 for _ in self.by_ref() {}
1377
1378 for replacement in self.replacement.by_ref() {
1381 self.parent.insert(self.removal_end, replacement);
1382 self.removal_end += 1;
1383 }
1384 }
1385}
1386
1387impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> {
1388 #[inline(always)]
1389 fn as_mut(&mut self) -> &mut [A::Item] {
1390 &mut *self
1391 }
1392}
1393
1394impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> {
1395 #[inline(always)]
1396 fn as_ref(&self) -> &[A::Item] {
1397 &*self
1398 }
1399}
1400
1401impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> {
1402 #[inline(always)]
1403 fn borrow(&self) -> &[A::Item] {
1404 &*self
1405 }
1406}
1407
1408impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> {
1409 #[inline(always)]
1410 fn borrow_mut(&mut self) -> &mut [A::Item] {
1411 &mut *self
1412 }
1413}
1414
1415impl<A: Array> Extend<A::Item> for ArrayVec<A> {
1416 #[inline]
1417 fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) {
1418 for t in iter {
1419 self.push(t)
1420 }
1421 }
1422}
1423
1424impl<A: Array> From<A> for ArrayVec<A> {
1425 #[inline(always)]
1426 fn from(data: A) -> Self {
1431 let len: u16 = data
1432 .as_slice()
1433 .len()
1434 .try_into()
1435 .expect("ArrayVec::from> length must be in range 0..=u16::MAX");
1436 Self { len, data }
1437 }
1438}
1439
1440#[derive(Debug, Copy, Clone)]
1443#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1444pub struct TryFromSliceError(());
1445
1446impl core::fmt::Display for TryFromSliceError {
1447 #[inline]
1448 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1449 f.write_str("could not convert slice to ArrayVec")
1450 }
1451}
1452
1453#[cfg(feature = "std")]
1454impl std::error::Error for TryFromSliceError {}
1455
1456impl<T, A> TryFrom<&'_ [T]> for ArrayVec<A>
1457where
1458 T: Clone + Default,
1459 A: Array<Item = T>,
1460{
1461 type Error = TryFromSliceError;
1462
1463 #[inline]
1464 fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
1467 if slice.len() > A::CAPACITY {
1468 Err(TryFromSliceError(()))
1469 } else {
1470 let mut arr = ArrayVec::new();
1471 arr.set_len(slice.len());
1479 arr.as_mut_slice().clone_from_slice(slice);
1480 Ok(arr)
1481 }
1482 }
1483}
1484
1485impl<A: Array> FromIterator<A::Item> for ArrayVec<A> {
1486 #[inline]
1487 fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self {
1488 let mut av = Self::default();
1489 for i in iter {
1490 av.push(i)
1491 }
1492 av
1493 }
1494}
1495
1496pub struct ArrayVecIterator<A: Array> {
1498 base: u16,
1499 tail: u16,
1500 data: A,
1501}
1502
1503impl<A: Array> ArrayVecIterator<A> {
1504 #[inline]
1506 #[must_use]
1507 pub fn as_slice(&self) -> &[A::Item] {
1508 &self.data.as_slice()[self.base as usize..self.tail as usize]
1509 }
1510}
1511impl<A: Array> FusedIterator for ArrayVecIterator<A> {}
1512impl<A: Array> Iterator for ArrayVecIterator<A> {
1513 type Item = A::Item;
1514 #[inline]
1515 fn next(&mut self) -> Option<Self::Item> {
1516 let slice =
1517 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1518 let itemref = slice.first_mut()?;
1519 self.base += 1;
1520 return Some(core::mem::take(itemref));
1521 }
1522 #[inline(always)]
1523 fn size_hint(&self) -> (usize, Option<usize>) {
1524 let s = self.tail - self.base;
1525 let s = s as usize;
1526 (s, Some(s))
1527 }
1528 #[inline(always)]
1529 fn count(self) -> usize {
1530 self.size_hint().0
1531 }
1532 #[inline]
1533 fn last(mut self) -> Option<Self::Item> {
1534 self.next_back()
1535 }
1536 #[inline]
1537 fn nth(&mut self, n: usize) -> Option<A::Item> {
1538 let slice = &mut self.data.as_slice_mut();
1539 let slice = &mut slice[self.base as usize..self.tail as usize];
1540
1541 if let Some(x) = slice.get_mut(n) {
1542 self.base += n as u16 + 1;
1544 return Some(core::mem::take(x));
1545 }
1546
1547 self.base = self.tail;
1548 return None;
1549 }
1550}
1551
1552impl<A: Array> DoubleEndedIterator for ArrayVecIterator<A> {
1553 #[inline]
1554 fn next_back(&mut self) -> Option<Self::Item> {
1555 let slice =
1556 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1557 let item = slice.last_mut()?;
1558 self.tail -= 1;
1559 return Some(core::mem::take(item));
1560 }
1561
1562 #[inline]
1563 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1564 let base = self.base as usize;
1565 let tail = self.tail as usize;
1566 let slice = &mut self.data.as_slice_mut()[base..tail];
1567 let n = n.saturating_add(1);
1568
1569 if let Some(n) = slice.len().checked_sub(n) {
1570 let item = &mut slice[n];
1571 self.tail = self.base + n as u16;
1573 return Some(core::mem::take(item));
1574 }
1575
1576 self.tail = self.base;
1577 return None;
1578 }
1579}
1580
1581impl<A: Array> ExactSizeIterator for ArrayVecIterator<A> {
1582 #[inline]
1583 fn len(&self) -> usize {
1584 self.size_hint().0
1585 }
1586}
1587
1588impl<A: Array> Debug for ArrayVecIterator<A>
1589where
1590 A::Item: Debug,
1591{
1592 #[allow(clippy::missing_inline_in_public_items)]
1593 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1594 f.debug_tuple("ArrayVecIterator").field(&self.as_slice()).finish()
1595 }
1596}
1597
1598#[cfg(feature = "defmt")]
1599#[cfg_attr(docs_rs, doc(cfg(feature = "defmt")))]
1600impl<A: Array> defmt::Format for ArrayVecIterator<A>
1601where
1602 A::Item: defmt::Format,
1603{
1604 fn format(&self, fmt: defmt::Formatter<'_>) {
1605 defmt::write!(fmt, "ArrayVecIterator({:?})", self.as_slice())
1606 }
1607}
1608
1609impl<A: Array> IntoIterator for ArrayVec<A> {
1610 type Item = A::Item;
1611 type IntoIter = ArrayVecIterator<A>;
1612 #[inline(always)]
1613 fn into_iter(self) -> Self::IntoIter {
1614 ArrayVecIterator { base: 0, tail: self.len, data: self.data }
1615 }
1616}
1617
1618impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
1619 type Item = &'a mut A::Item;
1620 type IntoIter = core::slice::IterMut<'a, A::Item>;
1621 #[inline(always)]
1622 fn into_iter(self) -> Self::IntoIter {
1623 self.iter_mut()
1624 }
1625}
1626
1627impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
1628 type Item = &'a A::Item;
1629 type IntoIter = core::slice::Iter<'a, A::Item>;
1630 #[inline(always)]
1631 fn into_iter(self) -> Self::IntoIter {
1632 self.iter()
1633 }
1634}
1635
1636impl<A: Array> PartialEq for ArrayVec<A>
1637where
1638 A::Item: PartialEq,
1639{
1640 #[inline]
1641 fn eq(&self, other: &Self) -> bool {
1642 self.as_slice().eq(other.as_slice())
1643 }
1644}
1645impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq {}
1646
1647impl<A: Array> PartialOrd for ArrayVec<A>
1648where
1649 A::Item: PartialOrd,
1650{
1651 #[inline]
1652 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1653 self.as_slice().partial_cmp(other.as_slice())
1654 }
1655}
1656impl<A: Array> Ord for ArrayVec<A>
1657where
1658 A::Item: Ord,
1659{
1660 #[inline]
1661 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1662 self.as_slice().cmp(other.as_slice())
1663 }
1664}
1665
1666impl<A: Array> PartialEq<&A> for ArrayVec<A>
1667where
1668 A::Item: PartialEq,
1669{
1670 #[inline]
1671 fn eq(&self, other: &&A) -> bool {
1672 self.as_slice().eq(other.as_slice())
1673 }
1674}
1675
1676impl<A: Array> PartialEq<&[A::Item]> for ArrayVec<A>
1677where
1678 A::Item: PartialEq,
1679{
1680 #[inline]
1681 fn eq(&self, other: &&[A::Item]) -> bool {
1682 self.as_slice().eq(*other)
1683 }
1684}
1685
1686impl<A: Array> Hash for ArrayVec<A>
1687where
1688 A::Item: Hash,
1689{
1690 #[inline]
1691 fn hash<H: Hasher>(&self, state: &mut H) {
1692 self.as_slice().hash(state)
1693 }
1694}
1695
1696#[cfg(feature = "experimental_write_impl")]
1697impl<A: Array<Item = u8>> core::fmt::Write for ArrayVec<A> {
1698 fn write_str(&mut self, s: &str) -> core::fmt::Result {
1699 let my_len = self.len();
1700 let str_len = s.as_bytes().len();
1701 if my_len + str_len <= A::CAPACITY {
1702 let remainder = &mut self.data.as_slice_mut()[my_len..];
1703 let target = &mut remainder[..str_len];
1704 target.copy_from_slice(s.as_bytes());
1705 Ok(())
1706 } else {
1707 Err(core::fmt::Error)
1708 }
1709 }
1710}
1711
1712impl<A: Array> Binary for ArrayVec<A>
1717where
1718 A::Item: Binary,
1719{
1720 #[allow(clippy::missing_inline_in_public_items)]
1721 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1722 write!(f, "[")?;
1723 if f.alternate() {
1724 write!(f, "\n ")?;
1725 }
1726 for (i, elem) in self.iter().enumerate() {
1727 if i > 0 {
1728 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1729 }
1730 Binary::fmt(elem, f)?;
1731 }
1732 if f.alternate() {
1733 write!(f, ",\n")?;
1734 }
1735 write!(f, "]")
1736 }
1737}
1738
1739impl<A: Array> Debug for ArrayVec<A>
1740where
1741 A::Item: Debug,
1742{
1743 #[allow(clippy::missing_inline_in_public_items)]
1744 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1745 <[A::Item] as Debug>::fmt(self.as_slice(), f)
1746 }
1747}
1748
1749#[cfg(feature = "defmt")]
1750#[cfg_attr(docs_rs, doc(cfg(feature = "defmt")))]
1751impl<A: Array> defmt::Format for ArrayVec<A>
1752where
1753 A::Item: defmt::Format,
1754{
1755 fn format(&self, fmt: defmt::Formatter<'_>) {
1756 defmt::Format::format(self.as_slice(), fmt)
1757 }
1758}
1759
1760impl<A: Array> Display for ArrayVec<A>
1761where
1762 A::Item: Display,
1763{
1764 #[allow(clippy::missing_inline_in_public_items)]
1765 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1766 write!(f, "[")?;
1767 if f.alternate() {
1768 write!(f, "\n ")?;
1769 }
1770 for (i, elem) in self.iter().enumerate() {
1771 if i > 0 {
1772 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1773 }
1774 Display::fmt(elem, f)?;
1775 }
1776 if f.alternate() {
1777 write!(f, ",\n")?;
1778 }
1779 write!(f, "]")
1780 }
1781}
1782
1783impl<A: Array> LowerExp for ArrayVec<A>
1784where
1785 A::Item: LowerExp,
1786{
1787 #[allow(clippy::missing_inline_in_public_items)]
1788 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1789 write!(f, "[")?;
1790 if f.alternate() {
1791 write!(f, "\n ")?;
1792 }
1793 for (i, elem) in self.iter().enumerate() {
1794 if i > 0 {
1795 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1796 }
1797 LowerExp::fmt(elem, f)?;
1798 }
1799 if f.alternate() {
1800 write!(f, ",\n")?;
1801 }
1802 write!(f, "]")
1803 }
1804}
1805
1806impl<A: Array> LowerHex for ArrayVec<A>
1807where
1808 A::Item: LowerHex,
1809{
1810 #[allow(clippy::missing_inline_in_public_items)]
1811 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1812 write!(f, "[")?;
1813 if f.alternate() {
1814 write!(f, "\n ")?;
1815 }
1816 for (i, elem) in self.iter().enumerate() {
1817 if i > 0 {
1818 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1819 }
1820 LowerHex::fmt(elem, f)?;
1821 }
1822 if f.alternate() {
1823 write!(f, ",\n")?;
1824 }
1825 write!(f, "]")
1826 }
1827}
1828
1829impl<A: Array> Octal for ArrayVec<A>
1830where
1831 A::Item: Octal,
1832{
1833 #[allow(clippy::missing_inline_in_public_items)]
1834 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1835 write!(f, "[")?;
1836 if f.alternate() {
1837 write!(f, "\n ")?;
1838 }
1839 for (i, elem) in self.iter().enumerate() {
1840 if i > 0 {
1841 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1842 }
1843 Octal::fmt(elem, f)?;
1844 }
1845 if f.alternate() {
1846 write!(f, ",\n")?;
1847 }
1848 write!(f, "]")
1849 }
1850}
1851
1852impl<A: Array> Pointer for ArrayVec<A>
1853where
1854 A::Item: Pointer,
1855{
1856 #[allow(clippy::missing_inline_in_public_items)]
1857 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1858 write!(f, "[")?;
1859 if f.alternate() {
1860 write!(f, "\n ")?;
1861 }
1862 for (i, elem) in self.iter().enumerate() {
1863 if i > 0 {
1864 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1865 }
1866 Pointer::fmt(elem, f)?;
1867 }
1868 if f.alternate() {
1869 write!(f, ",\n")?;
1870 }
1871 write!(f, "]")
1872 }
1873}
1874
1875impl<A: Array> UpperExp for ArrayVec<A>
1876where
1877 A::Item: UpperExp,
1878{
1879 #[allow(clippy::missing_inline_in_public_items)]
1880 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1881 write!(f, "[")?;
1882 if f.alternate() {
1883 write!(f, "\n ")?;
1884 }
1885 for (i, elem) in self.iter().enumerate() {
1886 if i > 0 {
1887 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1888 }
1889 UpperExp::fmt(elem, f)?;
1890 }
1891 if f.alternate() {
1892 write!(f, ",\n")?;
1893 }
1894 write!(f, "]")
1895 }
1896}
1897
1898impl<A: Array> UpperHex for ArrayVec<A>
1899where
1900 A::Item: UpperHex,
1901{
1902 #[allow(clippy::missing_inline_in_public_items)]
1903 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1904 write!(f, "[")?;
1905 if f.alternate() {
1906 write!(f, "\n ")?;
1907 }
1908 for (i, elem) in self.iter().enumerate() {
1909 if i > 0 {
1910 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1911 }
1912 UpperHex::fmt(elem, f)?;
1913 }
1914 if f.alternate() {
1915 write!(f, ",\n")?;
1916 }
1917 write!(f, "]")
1918 }
1919}
1920
1921#[cfg(feature = "alloc")]
1922use alloc::vec::Vec;
1923
1924#[cfg(all(feature = "alloc", feature = "rustc_1_57"))]
1925use alloc::collections::TryReserveError;
1926
1927#[cfg(feature = "alloc")]
1928impl<A: Array> ArrayVec<A> {
1929 #[inline]
1938 pub fn drain_to_vec_and_reserve(&mut self, n: usize) -> Vec<A::Item> {
1939 let cap = n + self.len();
1940 let mut v = Vec::with_capacity(cap);
1941 let iter = self.iter_mut().map(core::mem::take);
1942 v.extend(iter);
1943 self.set_len(0);
1944 return v;
1945 }
1946
1947 #[inline]
1963 #[cfg(feature = "rustc_1_57")]
1964 pub fn try_drain_to_vec_and_reserve(
1965 &mut self, n: usize,
1966 ) -> Result<Vec<A::Item>, TryReserveError> {
1967 let cap = n + self.len();
1968 let mut v = Vec::new();
1969 v.try_reserve(cap)?;
1970 let iter = self.iter_mut().map(core::mem::take);
1971 v.extend(iter);
1972 self.set_len(0);
1973 return Ok(v);
1974 }
1975
1976 #[inline]
1985 pub fn drain_to_vec(&mut self) -> Vec<A::Item> {
1986 self.drain_to_vec_and_reserve(0)
1987 }
1988
1989 #[inline]
2006 #[cfg(feature = "rustc_1_57")]
2007 pub fn try_drain_to_vec(&mut self) -> Result<Vec<A::Item>, TryReserveError> {
2008 self.try_drain_to_vec_and_reserve(0)
2009 }
2010}
2011
2012#[cfg(feature = "serde")]
2013struct ArrayVecVisitor<A: Array>(PhantomData<A>);
2014
2015#[cfg(feature = "serde")]
2016impl<'de, A: Array> Visitor<'de> for ArrayVecVisitor<A>
2017where
2018 A::Item: Deserialize<'de>,
2019{
2020 type Value = ArrayVec<A>;
2021
2022 fn expecting(
2023 &self, formatter: &mut core::fmt::Formatter,
2024 ) -> core::fmt::Result {
2025 formatter.write_str("a sequence")
2026 }
2027
2028 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
2029 where
2030 S: SeqAccess<'de>,
2031 {
2032 let mut new_arrayvec: ArrayVec<A> = Default::default();
2033
2034 let mut idx = 0usize;
2035 while let Some(value) = seq.next_element()? {
2036 if new_arrayvec.len() >= new_arrayvec.capacity() {
2037 return Err(DeserializeError::invalid_length(idx, &self));
2038 }
2039 new_arrayvec.push(value);
2040 idx = idx + 1;
2041 }
2042
2043 Ok(new_arrayvec)
2044 }
2045}
2046
2047#[cfg(test)]
2048mod test {
2049 use super::*;
2050
2051 #[test]
2052 fn retain_mut_empty_vec() {
2053 let mut av: ArrayVec<[i32; 4]> = ArrayVec::new();
2054 av.retain_mut(|&mut x| x % 2 == 0);
2055 assert_eq!(av.len(), 0);
2056 }
2057
2058 #[test]
2059 fn retain_mut_all_elements() {
2060 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 2, 4, 6, 8);
2061 av.retain_mut(|&mut x| x % 2 == 0);
2062 assert_eq!(av.len(), 4);
2063 assert_eq!(av.as_slice(), &[2, 4, 6, 8]);
2064 }
2065
2066 #[test]
2067 fn retain_mut_some_elements() {
2068 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 2, 3, 4);
2069 av.retain_mut(|&mut x| x % 2 == 0);
2070 assert_eq!(av.len(), 2);
2071 assert_eq!(av.as_slice(), &[2, 4]);
2072 }
2073
2074 #[test]
2075 fn retain_mut_no_elements() {
2076 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 3, 5, 7);
2077 av.retain_mut(|&mut x| x % 2 == 0);
2078 assert_eq!(av.len(), 0);
2079 }
2080
2081 #[test]
2082 fn retain_mut_zero_capacity() {
2083 let mut av: ArrayVec<[i32; 0]> = ArrayVec::new();
2084 av.retain_mut(|&mut x| x % 2 == 0);
2085 assert_eq!(av.len(), 0);
2086 }
2087
2088 #[cfg(feature = "alloc")]
2089 #[test]
2090 fn array_like_debug() {
2091 #[derive(Debug, Default, Copy, Clone)]
2092 struct S {
2093 x: u8,
2094 y: u8,
2095 }
2096
2097 use core::fmt::Write;
2098
2099 let mut ar: [S; 2] = [S { x: 1, y: 2 }, S { x: 3, y: 4 }];
2100 let mut buf_ar = alloc::string::String::new();
2101 write!(&mut buf_ar, "{ar:#?}");
2102
2103 let av: ArrayVec<[S; 2]> = ArrayVec::from(ar);
2104 let mut buf_av = alloc::string::String::new();
2105 write!(&mut buf_av, "{av:#?}");
2106
2107 assert_eq!(buf_av, buf_ar)
2108 }
2109}