1use super::*;
2use core::convert::{TryFrom, TryInto};
3
4#[cfg(feature = "serde")]
5use core::marker::PhantomData;
6#[cfg(feature = "serde")]
7use serde::de::{
8 Deserialize, Deserializer, Error as DeserializeError, SeqAccess, Visitor,
9};
10#[cfg(feature = "serde")]
11use serde::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 #[must_use]
159 fn deref(&self) -> &Self::Target {
160 &self.data.as_slice()[..self.len as usize]
161 }
162}
163
164impl<A: Array> DerefMut for ArrayVec<A> {
165 #[inline(always)]
166 #[must_use]
167 fn deref_mut(&mut self) -> &mut Self::Target {
168 &mut self.data.as_slice_mut()[..self.len as usize]
169 }
170}
171
172impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for ArrayVec<A> {
173 type Output = <I as SliceIndex<[A::Item]>>::Output;
174 #[inline(always)]
175 #[must_use]
176 fn index(&self, index: I) -> &Self::Output {
177 &self.deref()[index]
178 }
179}
180
181impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for ArrayVec<A> {
182 #[inline(always)]
183 #[must_use]
184 fn index_mut(&mut self, index: I) -> &mut Self::Output {
185 &mut self.deref_mut()[index]
186 }
187}
188
189#[cfg(feature = "serde")]
190#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
191impl<A: Array> Serialize for ArrayVec<A>
192where
193 A::Item: Serialize,
194{
195 #[must_use]
196 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
197 where
198 S: Serializer,
199 {
200 let mut seq = serializer.serialize_seq(Some(self.len()))?;
201 for element in self.iter() {
202 seq.serialize_element(element)?;
203 }
204 seq.end()
205 }
206}
207
208#[cfg(feature = "serde")]
209#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
210impl<'de, A: Array> Deserialize<'de> for ArrayVec<A>
211where
212 A::Item: Deserialize<'de>,
213{
214 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
215 where
216 D: Deserializer<'de>,
217 {
218 deserializer.deserialize_seq(ArrayVecVisitor(PhantomData))
219 }
220}
221
222#[cfg(feature = "arbitrary")]
223#[cfg_attr(docs_rs, doc(cfg(feature = "arbitrary")))]
224impl<'a, A> arbitrary::Arbitrary<'a> for ArrayVec<A>
225where
226 A: Array,
227 A::Item: arbitrary::Arbitrary<'a>,
228{
229 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
230 let max_len = A::CAPACITY.min(u16::MAX as usize) as u16;
231 let len = u.int_in_range::<u16>(0..=max_len)?;
232 let mut self_: Self = Default::default();
233 for _ in 0..len {
234 self_.push(u.arbitrary()?);
235 }
236 Ok(self_)
237 }
238
239 fn size_hint(depth: usize) -> (usize, Option<usize>) {
240 arbitrary::size_hint::recursion_guard(depth, |depth| {
241 let max_len = A::CAPACITY.min(u16::MAX as usize);
242 let inner = A::Item::size_hint(depth).1;
243 (0, inner.map(|inner| 2 + max_len * inner))
244 })
245 }
246}
247
248impl<A: Array> ArrayVec<A> {
249 #[inline]
264 pub fn append(&mut self, other: &mut Self) {
265 assert!(
266 self.try_append(other).is_none(),
267 "ArrayVec::append> total length {} exceeds capacity {}!",
268 self.len() + other.len(),
269 A::CAPACITY
270 );
271 }
272
273 #[inline]
290 pub fn try_append<'other>(
291 &mut self, other: &'other mut Self,
292 ) -> Option<&'other mut Self> {
293 let new_len = self.len() + other.len();
294 if new_len > A::CAPACITY {
295 return Some(other);
296 }
297
298 let iter = other.iter_mut().map(core::mem::take);
299 for item in iter {
300 self.push(item);
301 }
302
303 other.set_len(0);
304
305 return None;
306 }
307
308 #[inline(always)]
314 #[must_use]
315 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
316 self.data.as_slice_mut().as_mut_ptr()
317 }
318
319 #[inline(always)]
321 #[must_use]
322 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
323 self.deref_mut()
324 }
325
326 #[inline(always)]
332 #[must_use]
333 pub fn as_ptr(&self) -> *const A::Item {
334 self.data.as_slice().as_ptr()
335 }
336
337 #[inline(always)]
339 #[must_use]
340 pub fn as_slice(&self) -> &[A::Item] {
341 self.deref()
342 }
343
344 #[inline(always)]
349 #[must_use]
350 pub fn capacity(&self) -> usize {
351 self.data.as_slice().len().min(u16::MAX as usize)
355 }
356
357 #[inline(always)]
359 pub fn clear(&mut self) {
360 self.truncate(0)
361 }
362
363 #[inline]
382 pub fn drain<R>(&mut self, range: R) -> ArrayVecDrain<'_, A::Item>
383 where
384 R: RangeBounds<usize>,
385 {
386 ArrayVecDrain::new(self, range)
387 }
388
389 #[inline]
415 pub fn into_inner(self) -> A {
416 self.data
417 }
418
419 #[inline]
424 pub fn extend_from_slice(&mut self, sli: &[A::Item])
425 where
426 A::Item: Clone,
427 {
428 if sli.is_empty() {
429 return;
430 }
431
432 let new_len = self.len as usize + sli.len();
433 assert!(
434 new_len <= A::CAPACITY,
435 "ArrayVec::extend_from_slice> total length {} exceeds capacity {}!",
436 new_len,
437 A::CAPACITY
438 );
439
440 let target = &mut self.data.as_slice_mut()[self.len as usize..new_len];
441 target.clone_from_slice(sli);
442 self.set_len(new_len);
443 }
444
445 #[inline]
471 pub fn fill<I: IntoIterator<Item = A::Item>>(
472 &mut self, iter: I,
473 ) -> I::IntoIter {
474 let mut iter = iter.into_iter();
479 let mut pushed = 0;
480 let to_take = self.capacity() - self.len();
481 let target = &mut self.data.as_slice_mut()[self.len as usize..];
482 for element in iter.by_ref().take(to_take) {
483 target[pushed] = element;
484 pushed += 1;
485 }
486 self.len += pushed as u16;
487 iter
488 }
489
490 #[inline]
499 #[must_use]
500 #[allow(clippy::match_wild_err_arm)]
501 pub fn from_array_len(data: A, len: usize) -> Self {
502 match Self::try_from_array_len(data, len) {
503 Ok(out) => out,
504 Err(_) => panic!(
505 "ArrayVec::from_array_len> length {} exceeds capacity {}!",
506 len,
507 A::CAPACITY
508 ),
509 }
510 }
511
512 #[inline]
529 pub fn insert(&mut self, index: usize, item: A::Item) {
530 let x = self.try_insert(index, item);
531 assert!(x.is_none(), "ArrayVec::insert> capacity overflow!");
532 }
533
534 #[inline]
551 pub fn try_insert(
552 &mut self, index: usize, mut item: A::Item,
553 ) -> Option<A::Item> {
554 assert!(
555 index <= self.len as usize,
556 "ArrayVec::try_insert> index {} is out of bounds {}",
557 index,
558 self.len
559 );
560
561 if (self.len as usize) < A::CAPACITY {
569 self.len += 1;
570 } else {
571 return Some(item);
572 }
573
574 let target = &mut self.as_mut_slice()[index..];
575 for i in 0..target.len() {
576 core::mem::swap(&mut item, &mut target[i]);
577 }
578 return None;
579 }
580
581 #[inline(always)]
583 #[must_use]
584 pub fn is_empty(&self) -> bool {
585 self.len == 0
586 }
587
588 #[inline(always)]
590 #[must_use]
591 pub fn len(&self) -> usize {
592 self.len as usize
593 }
594
595 #[inline(always)]
597 #[must_use]
598 pub fn new() -> Self {
599 Self::default()
600 }
601
602 #[inline]
616 pub fn pop(&mut self) -> Option<A::Item> {
617 if self.len > 0 {
618 self.len -= 1;
619 let out =
620 core::mem::take(&mut self.data.as_slice_mut()[self.len as usize]);
621 Some(out)
622 } else {
623 None
624 }
625 }
626
627 #[inline(always)]
644 pub fn push(&mut self, val: A::Item) {
645 let x = self.try_push(val);
646 assert!(x.is_none(), "ArrayVec::push> capacity overflow!");
647 }
648
649 #[inline(always)]
663 pub fn try_push(&mut self, val: A::Item) -> Option<A::Item> {
664 debug_assert!(self.len as usize <= A::CAPACITY);
665
666 let itemref = match self.data.as_slice_mut().get_mut(self.len as usize) {
667 None => return Some(val),
668 Some(x) => x,
669 };
670
671 *itemref = val;
672 self.len += 1;
673 return None;
674 }
675
676 #[inline]
693 pub fn remove(&mut self, index: usize) -> A::Item {
694 let targets: &mut [A::Item] = &mut self.deref_mut()[index..];
695 let item = core::mem::take(&mut targets[0]);
696
697 for i in 0..targets.len() - 1 {
705 targets.swap(i, i + 1);
706 }
707 self.len -= 1;
708 item
709 }
710
711 #[inline]
728 pub fn resize(&mut self, new_len: usize, new_val: A::Item)
729 where
730 A::Item: Clone,
731 {
732 self.resize_with(new_len, || new_val.clone())
733 }
734
735 #[inline]
758 pub fn resize_with<F: FnMut() -> A::Item>(
759 &mut self, new_len: usize, mut f: F,
760 ) {
761 match new_len.checked_sub(self.len as usize) {
762 None => self.truncate(new_len),
763 Some(new_elements) => {
764 for _ in 0..new_elements {
765 self.push(f());
766 }
767 }
768 }
769 }
770
771 #[inline]
783 pub fn retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F) {
784 struct JoinOnDrop<'vec, Item> {
787 items: &'vec mut [Item],
788 done_end: usize,
789 tail_start: usize,
791 }
792
793 impl<Item> Drop for JoinOnDrop<'_, Item> {
794 fn drop(&mut self) {
795 self.items[self.done_end..].rotate_left(self.tail_start);
796 }
797 }
798
799 let mut rest = JoinOnDrop {
800 items: &mut self.data.as_slice_mut()[..self.len as usize],
801 done_end: 0,
802 tail_start: 0,
803 };
804
805 let len = self.len as usize;
806 for idx in 0..len {
807 if !acceptable(&rest.items[idx]) {
809 let _ = core::mem::take(&mut rest.items[idx]);
810 self.len -= 1;
811 rest.tail_start += 1;
812 } else {
813 rest.items.swap(rest.done_end, idx);
814 rest.done_end += 1;
815 }
816 }
817 }
818
819 #[inline]
837 pub fn retain_mut<F>(&mut self, mut acceptable: F)
838 where
839 F: FnMut(&mut A::Item) -> bool,
840 {
841 struct JoinOnDrop<'vec, Item> {
844 items: &'vec mut [Item],
845 done_end: usize,
846 tail_start: usize,
848 }
849
850 impl<Item> Drop for JoinOnDrop<'_, Item> {
851 fn drop(&mut self) {
852 self.items[self.done_end..].rotate_left(self.tail_start);
853 }
854 }
855
856 let mut rest = JoinOnDrop {
857 items: &mut self.data.as_slice_mut()[..self.len as usize],
858 done_end: 0,
859 tail_start: 0,
860 };
861
862 let len = self.len as usize;
863 for idx in 0..len {
864 if !acceptable(&mut rest.items[idx]) {
866 let _ = core::mem::take(&mut rest.items[idx]);
867 self.len -= 1;
868 rest.tail_start += 1;
869 } else {
870 rest.items.swap(rest.done_end, idx);
871 rest.done_end += 1;
872 }
873 }
874 }
875
876 #[inline(always)]
887 pub fn set_len(&mut self, new_len: usize) {
888 if new_len > A::CAPACITY {
889 panic!(
894 "ArrayVec::set_len> new length {} exceeds capacity {}",
895 new_len,
896 A::CAPACITY
897 )
898 }
899
900 let new_len: u16 = new_len
901 .try_into()
902 .expect("ArrayVec::set_len> new length is not in range 0..=u16::MAX");
903 self.len = new_len;
904 }
905
906 #[inline]
924 pub fn split_off(&mut self, at: usize) -> Self {
925 if at > self.len() {
927 panic!(
928 "ArrayVec::split_off> at value {} exceeds length of {}",
929 at, self.len
930 );
931 }
932 let mut new = Self::default();
933 let moves = &mut self.as_mut_slice()[at..];
934 let split_len = moves.len();
935 let targets = &mut new.data.as_slice_mut()[..split_len];
936 moves.swap_with_slice(targets);
937
938 new.len = split_len as u16;
940 self.len = at as u16;
941 new
942 }
943
944 #[inline]
971 pub fn splice<R, I>(
972 &mut self, range: R, replacement: I,
973 ) -> ArrayVecSplice<'_, A, core::iter::Fuse<I::IntoIter>>
974 where
975 R: RangeBounds<usize>,
976 I: IntoIterator<Item = A::Item>,
977 {
978 use core::ops::Bound;
979 let start = match range.start_bound() {
980 Bound::Included(x) => *x,
981 Bound::Excluded(x) => x.saturating_add(1),
982 Bound::Unbounded => 0,
983 };
984 let end = match range.end_bound() {
985 Bound::Included(x) => x.saturating_add(1),
986 Bound::Excluded(x) => *x,
987 Bound::Unbounded => self.len(),
988 };
989 assert!(
990 start <= end,
991 "ArrayVec::splice> Illegal range, {} to {}",
992 start,
993 end
994 );
995 assert!(
996 end <= self.len(),
997 "ArrayVec::splice> Range ends at {} but length is only {}!",
998 end,
999 self.len()
1000 );
1001
1002 ArrayVecSplice {
1003 removal_start: start,
1004 removal_end: end,
1005 parent: self,
1006 replacement: replacement.into_iter().fuse(),
1007 }
1008 }
1009
1010 #[inline]
1027 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1028 assert!(
1029 index < self.len(),
1030 "ArrayVec::swap_remove> index {} is out of bounds {}",
1031 index,
1032 self.len
1033 );
1034 if index == self.len() - 1 {
1035 self.pop().unwrap()
1036 } else {
1037 let i = self.pop().unwrap();
1038 replace(&mut self[index], i)
1039 }
1040 }
1041
1042 #[inline]
1046 pub fn truncate(&mut self, new_len: usize) {
1047 if new_len >= self.len as usize {
1048 return;
1049 }
1050
1051 if needs_drop::<A::Item>() {
1052 let len = self.len as usize;
1053 self.data.as_slice_mut()[new_len..len]
1054 .iter_mut()
1055 .map(core::mem::take)
1056 .for_each(drop);
1057 }
1058
1059 self.len = new_len as u16;
1061 }
1062
1063 #[inline]
1073 pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1074 if len <= A::CAPACITY {
1076 Ok(Self { data, len: len as u16 })
1077 } else {
1078 Err(data)
1079 }
1080 }
1081}
1082
1083impl<A> ArrayVec<A> {
1084 #[inline]
1108 #[must_use]
1109 pub const fn from_array_empty(data: A) -> Self {
1110 Self { data, len: 0 }
1111 }
1112}
1113
1114#[cfg(feature = "grab_spare_slice")]
1115impl<A: Array> ArrayVec<A> {
1116 #[inline(always)]
1130 pub fn grab_spare_slice(&self) -> &[A::Item] {
1131 &self.data.as_slice()[self.len as usize..]
1132 }
1133
1134 #[inline(always)]
1146 pub fn grab_spare_slice_mut(&mut self) -> &mut [A::Item] {
1147 &mut self.data.as_slice_mut()[self.len as usize..]
1148 }
1149}
1150
1151#[cfg(feature = "nightly_slice_partition_dedup")]
1152impl<A: Array> ArrayVec<A> {
1153 #[inline(always)]
1155 pub fn dedup(&mut self)
1156 where
1157 A::Item: PartialEq,
1158 {
1159 self.dedup_by(|a, b| a == b)
1160 }
1161
1162 #[inline(always)]
1164 pub fn dedup_by<F>(&mut self, same_bucket: F)
1165 where
1166 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1167 {
1168 let len = {
1169 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1170 dedup.len()
1171 };
1172 self.truncate(len);
1173 }
1174
1175 #[inline(always)]
1177 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1178 where
1179 F: FnMut(&mut A::Item) -> K,
1180 K: PartialEq,
1181 {
1182 self.dedup_by(|a, b| key(a) == key(b))
1183 }
1184}
1185
1186impl<A> ArrayVec<A> {
1187 #[inline(always)]
1192 #[must_use]
1193 pub const fn as_inner(&self) -> &A {
1194 &self.data
1195 }
1196}
1197
1198pub struct ArrayVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> {
1201 parent: &'p mut ArrayVec<A>,
1202 removal_start: usize,
1203 removal_end: usize,
1204 replacement: I,
1205}
1206
1207impl<'p, A: Array, I: Iterator<Item = A::Item>> Iterator
1208 for ArrayVecSplice<'p, A, I>
1209{
1210 type Item = A::Item;
1211
1212 #[inline]
1213 fn next(&mut self) -> Option<A::Item> {
1214 if self.removal_start < self.removal_end {
1215 match self.replacement.next() {
1216 Some(replacement) => {
1217 let removed = core::mem::replace(
1218 &mut self.parent[self.removal_start],
1219 replacement,
1220 );
1221 self.removal_start += 1;
1222 Some(removed)
1223 }
1224 None => {
1225 let removed = self.parent.remove(self.removal_start);
1226 self.removal_end -= 1;
1227 Some(removed)
1228 }
1229 }
1230 } else {
1231 None
1232 }
1233 }
1234
1235 #[inline]
1236 fn size_hint(&self) -> (usize, Option<usize>) {
1237 let len = self.len();
1238 (len, Some(len))
1239 }
1240}
1241
1242impl<'p, A, I> ExactSizeIterator for ArrayVecSplice<'p, A, I>
1243where
1244 A: Array,
1245 I: Iterator<Item = A::Item>,
1246{
1247 #[inline]
1248 fn len(&self) -> usize {
1249 self.removal_end - self.removal_start
1250 }
1251}
1252
1253impl<'p, A, I> FusedIterator for ArrayVecSplice<'p, A, I>
1254where
1255 A: Array,
1256 I: Iterator<Item = A::Item>,
1257{
1258}
1259
1260impl<'p, A, I> DoubleEndedIterator for ArrayVecSplice<'p, A, I>
1261where
1262 A: Array,
1263 I: Iterator<Item = A::Item> + DoubleEndedIterator,
1264{
1265 #[inline]
1266 fn next_back(&mut self) -> Option<A::Item> {
1267 if self.removal_start < self.removal_end {
1268 match self.replacement.next_back() {
1269 Some(replacement) => {
1270 let removed = core::mem::replace(
1271 &mut self.parent[self.removal_end - 1],
1272 replacement,
1273 );
1274 self.removal_end -= 1;
1275 Some(removed)
1276 }
1277 None => {
1278 let removed = self.parent.remove(self.removal_end - 1);
1279 self.removal_end -= 1;
1280 Some(removed)
1281 }
1282 }
1283 } else {
1284 None
1285 }
1286 }
1287}
1288
1289impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop
1290 for ArrayVecSplice<'p, A, I>
1291{
1292 #[inline]
1293 fn drop(&mut self) {
1294 for _ in self.by_ref() {}
1295
1296 for replacement in self.replacement.by_ref() {
1299 self.parent.insert(self.removal_end, replacement);
1300 self.removal_end += 1;
1301 }
1302 }
1303}
1304
1305impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> {
1306 #[inline(always)]
1307 #[must_use]
1308 fn as_mut(&mut self) -> &mut [A::Item] {
1309 &mut *self
1310 }
1311}
1312
1313impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> {
1314 #[inline(always)]
1315 #[must_use]
1316 fn as_ref(&self) -> &[A::Item] {
1317 &*self
1318 }
1319}
1320
1321impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> {
1322 #[inline(always)]
1323 #[must_use]
1324 fn borrow(&self) -> &[A::Item] {
1325 &*self
1326 }
1327}
1328
1329impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> {
1330 #[inline(always)]
1331 #[must_use]
1332 fn borrow_mut(&mut self) -> &mut [A::Item] {
1333 &mut *self
1334 }
1335}
1336
1337impl<A: Array> Extend<A::Item> for ArrayVec<A> {
1338 #[inline]
1339 fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) {
1340 for t in iter {
1341 self.push(t)
1342 }
1343 }
1344}
1345
1346impl<A: Array> From<A> for ArrayVec<A> {
1347 #[inline(always)]
1348 #[must_use]
1349 fn from(data: A) -> Self {
1354 let len: u16 = data
1355 .as_slice()
1356 .len()
1357 .try_into()
1358 .expect("ArrayVec::from> length must be in range 0..=u16::MAX");
1359 Self { len, data }
1360 }
1361}
1362
1363#[derive(Debug, Copy, Clone)]
1366pub struct TryFromSliceError(());
1367
1368impl core::fmt::Display for TryFromSliceError {
1369 #[inline]
1370 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1371 f.write_str("could not convert slice to ArrayVec")
1372 }
1373}
1374
1375#[cfg(feature = "std")]
1376impl std::error::Error for TryFromSliceError {}
1377
1378impl<T, A> TryFrom<&'_ [T]> for ArrayVec<A>
1379where
1380 T: Clone + Default,
1381 A: Array<Item = T>,
1382{
1383 type Error = TryFromSliceError;
1384
1385 #[inline]
1386 fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
1389 if slice.len() > A::CAPACITY {
1390 Err(TryFromSliceError(()))
1391 } else {
1392 let mut arr = ArrayVec::new();
1393 arr.set_len(slice.len());
1401 arr.as_mut_slice().clone_from_slice(slice);
1402 Ok(arr)
1403 }
1404 }
1405}
1406
1407impl<A: Array> FromIterator<A::Item> for ArrayVec<A> {
1408 #[inline]
1409 #[must_use]
1410 fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self {
1411 let mut av = Self::default();
1412 for i in iter {
1413 av.push(i)
1414 }
1415 av
1416 }
1417}
1418
1419pub struct ArrayVecIterator<A: Array> {
1421 base: u16,
1422 tail: u16,
1423 data: A,
1424}
1425
1426impl<A: Array> ArrayVecIterator<A> {
1427 #[inline]
1429 #[must_use]
1430 pub fn as_slice(&self) -> &[A::Item] {
1431 &self.data.as_slice()[self.base as usize..self.tail as usize]
1432 }
1433}
1434impl<A: Array> FusedIterator for ArrayVecIterator<A> {}
1435impl<A: Array> Iterator for ArrayVecIterator<A> {
1436 type Item = A::Item;
1437 #[inline]
1438 fn next(&mut self) -> Option<Self::Item> {
1439 let slice =
1440 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1441 let itemref = slice.first_mut()?;
1442 self.base += 1;
1443 return Some(core::mem::take(itemref));
1444 }
1445 #[inline(always)]
1446 #[must_use]
1447 fn size_hint(&self) -> (usize, Option<usize>) {
1448 let s = self.tail - self.base;
1449 let s = s as usize;
1450 (s, Some(s))
1451 }
1452 #[inline(always)]
1453 fn count(self) -> usize {
1454 self.size_hint().0
1455 }
1456 #[inline]
1457 fn last(mut self) -> Option<Self::Item> {
1458 self.next_back()
1459 }
1460 #[inline]
1461 fn nth(&mut self, n: usize) -> Option<A::Item> {
1462 let slice = &mut self.data.as_slice_mut();
1463 let slice = &mut slice[self.base as usize..self.tail as usize];
1464
1465 if let Some(x) = slice.get_mut(n) {
1466 self.base += n as u16 + 1;
1468 return Some(core::mem::take(x));
1469 }
1470
1471 self.base = self.tail;
1472 return None;
1473 }
1474}
1475
1476impl<A: Array> DoubleEndedIterator for ArrayVecIterator<A> {
1477 #[inline]
1478 fn next_back(&mut self) -> Option<Self::Item> {
1479 let slice =
1480 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1481 let item = slice.last_mut()?;
1482 self.tail -= 1;
1483 return Some(core::mem::take(item));
1484 }
1485
1486 #[inline]
1487 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1488 let base = self.base as usize;
1489 let tail = self.tail as usize;
1490 let slice = &mut self.data.as_slice_mut()[base..tail];
1491 let n = n.saturating_add(1);
1492
1493 if let Some(n) = slice.len().checked_sub(n) {
1494 let item = &mut slice[n];
1495 self.tail = self.base + n as u16;
1497 return Some(core::mem::take(item));
1498 }
1499
1500 self.tail = self.base;
1501 return None;
1502 }
1503}
1504
1505impl<A: Array> ExactSizeIterator for ArrayVecIterator<A> {
1506 #[inline]
1507 fn len(&self) -> usize {
1508 self.size_hint().0
1509 }
1510}
1511
1512impl<A: Array> Debug for ArrayVecIterator<A>
1513where
1514 A::Item: Debug,
1515{
1516 #[allow(clippy::missing_inline_in_public_items)]
1517 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1518 f.debug_tuple("ArrayVecIterator").field(&self.as_slice()).finish()
1519 }
1520}
1521
1522impl<A: Array> IntoIterator for ArrayVec<A> {
1523 type Item = A::Item;
1524 type IntoIter = ArrayVecIterator<A>;
1525 #[inline(always)]
1526 #[must_use]
1527 fn into_iter(self) -> Self::IntoIter {
1528 ArrayVecIterator { base: 0, tail: self.len, data: self.data }
1529 }
1530}
1531
1532impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
1533 type Item = &'a mut A::Item;
1534 type IntoIter = core::slice::IterMut<'a, A::Item>;
1535 #[inline(always)]
1536 #[must_use]
1537 fn into_iter(self) -> Self::IntoIter {
1538 self.iter_mut()
1539 }
1540}
1541
1542impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
1543 type Item = &'a A::Item;
1544 type IntoIter = core::slice::Iter<'a, A::Item>;
1545 #[inline(always)]
1546 #[must_use]
1547 fn into_iter(self) -> Self::IntoIter {
1548 self.iter()
1549 }
1550}
1551
1552impl<A: Array> PartialEq for ArrayVec<A>
1553where
1554 A::Item: PartialEq,
1555{
1556 #[inline]
1557 #[must_use]
1558 fn eq(&self, other: &Self) -> bool {
1559 self.as_slice().eq(other.as_slice())
1560 }
1561}
1562impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq {}
1563
1564impl<A: Array> PartialOrd for ArrayVec<A>
1565where
1566 A::Item: PartialOrd,
1567{
1568 #[inline]
1569 #[must_use]
1570 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1571 self.as_slice().partial_cmp(other.as_slice())
1572 }
1573}
1574impl<A: Array> Ord for ArrayVec<A>
1575where
1576 A::Item: Ord,
1577{
1578 #[inline]
1579 #[must_use]
1580 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1581 self.as_slice().cmp(other.as_slice())
1582 }
1583}
1584
1585impl<A: Array> PartialEq<&A> for ArrayVec<A>
1586where
1587 A::Item: PartialEq,
1588{
1589 #[inline]
1590 #[must_use]
1591 fn eq(&self, other: &&A) -> bool {
1592 self.as_slice().eq(other.as_slice())
1593 }
1594}
1595
1596impl<A: Array> PartialEq<&[A::Item]> for ArrayVec<A>
1597where
1598 A::Item: PartialEq,
1599{
1600 #[inline]
1601 #[must_use]
1602 fn eq(&self, other: &&[A::Item]) -> bool {
1603 self.as_slice().eq(*other)
1604 }
1605}
1606
1607impl<A: Array> Hash for ArrayVec<A>
1608where
1609 A::Item: Hash,
1610{
1611 #[inline]
1612 fn hash<H: Hasher>(&self, state: &mut H) {
1613 self.as_slice().hash(state)
1614 }
1615}
1616
1617#[cfg(feature = "experimental_write_impl")]
1618impl<A: Array<Item = u8>> core::fmt::Write for ArrayVec<A> {
1619 fn write_str(&mut self, s: &str) -> core::fmt::Result {
1620 let my_len = self.len();
1621 let str_len = s.as_bytes().len();
1622 if my_len + str_len <= A::CAPACITY {
1623 let remainder = &mut self.data.as_slice_mut()[my_len..];
1624 let target = &mut remainder[..str_len];
1625 target.copy_from_slice(s.as_bytes());
1626 Ok(())
1627 } else {
1628 Err(core::fmt::Error)
1629 }
1630 }
1631}
1632
1633impl<A: Array> Binary for ArrayVec<A>
1638where
1639 A::Item: Binary,
1640{
1641 #[allow(clippy::missing_inline_in_public_items)]
1642 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1643 write!(f, "[")?;
1644 if f.alternate() {
1645 write!(f, "\n ")?;
1646 }
1647 for (i, elem) in self.iter().enumerate() {
1648 if i > 0 {
1649 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1650 }
1651 Binary::fmt(elem, f)?;
1652 }
1653 if f.alternate() {
1654 write!(f, ",\n")?;
1655 }
1656 write!(f, "]")
1657 }
1658}
1659
1660impl<A: Array> Debug for ArrayVec<A>
1661where
1662 A::Item: Debug,
1663{
1664 #[allow(clippy::missing_inline_in_public_items)]
1665 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1666 write!(f, "[")?;
1667 if f.alternate() && !self.is_empty() {
1668 write!(f, "\n ")?;
1669 }
1670 for (i, elem) in self.iter().enumerate() {
1671 if i > 0 {
1672 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1673 }
1674 Debug::fmt(elem, f)?;
1675 }
1676 if f.alternate() && !self.is_empty() {
1677 write!(f, ",\n")?;
1678 }
1679 write!(f, "]")
1680 }
1681}
1682
1683impl<A: Array> Display for ArrayVec<A>
1684where
1685 A::Item: Display,
1686{
1687 #[allow(clippy::missing_inline_in_public_items)]
1688 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1689 write!(f, "[")?;
1690 if f.alternate() {
1691 write!(f, "\n ")?;
1692 }
1693 for (i, elem) in self.iter().enumerate() {
1694 if i > 0 {
1695 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1696 }
1697 Display::fmt(elem, f)?;
1698 }
1699 if f.alternate() {
1700 write!(f, ",\n")?;
1701 }
1702 write!(f, "]")
1703 }
1704}
1705
1706impl<A: Array> LowerExp for ArrayVec<A>
1707where
1708 A::Item: LowerExp,
1709{
1710 #[allow(clippy::missing_inline_in_public_items)]
1711 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1712 write!(f, "[")?;
1713 if f.alternate() {
1714 write!(f, "\n ")?;
1715 }
1716 for (i, elem) in self.iter().enumerate() {
1717 if i > 0 {
1718 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1719 }
1720 LowerExp::fmt(elem, f)?;
1721 }
1722 if f.alternate() {
1723 write!(f, ",\n")?;
1724 }
1725 write!(f, "]")
1726 }
1727}
1728
1729impl<A: Array> LowerHex for ArrayVec<A>
1730where
1731 A::Item: LowerHex,
1732{
1733 #[allow(clippy::missing_inline_in_public_items)]
1734 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1735 write!(f, "[")?;
1736 if f.alternate() {
1737 write!(f, "\n ")?;
1738 }
1739 for (i, elem) in self.iter().enumerate() {
1740 if i > 0 {
1741 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1742 }
1743 LowerHex::fmt(elem, f)?;
1744 }
1745 if f.alternate() {
1746 write!(f, ",\n")?;
1747 }
1748 write!(f, "]")
1749 }
1750}
1751
1752impl<A: Array> Octal for ArrayVec<A>
1753where
1754 A::Item: Octal,
1755{
1756 #[allow(clippy::missing_inline_in_public_items)]
1757 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1758 write!(f, "[")?;
1759 if f.alternate() {
1760 write!(f, "\n ")?;
1761 }
1762 for (i, elem) in self.iter().enumerate() {
1763 if i > 0 {
1764 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1765 }
1766 Octal::fmt(elem, f)?;
1767 }
1768 if f.alternate() {
1769 write!(f, ",\n")?;
1770 }
1771 write!(f, "]")
1772 }
1773}
1774
1775impl<A: Array> Pointer for ArrayVec<A>
1776where
1777 A::Item: Pointer,
1778{
1779 #[allow(clippy::missing_inline_in_public_items)]
1780 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1781 write!(f, "[")?;
1782 if f.alternate() {
1783 write!(f, "\n ")?;
1784 }
1785 for (i, elem) in self.iter().enumerate() {
1786 if i > 0 {
1787 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1788 }
1789 Pointer::fmt(elem, f)?;
1790 }
1791 if f.alternate() {
1792 write!(f, ",\n")?;
1793 }
1794 write!(f, "]")
1795 }
1796}
1797
1798impl<A: Array> UpperExp for ArrayVec<A>
1799where
1800 A::Item: UpperExp,
1801{
1802 #[allow(clippy::missing_inline_in_public_items)]
1803 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1804 write!(f, "[")?;
1805 if f.alternate() {
1806 write!(f, "\n ")?;
1807 }
1808 for (i, elem) in self.iter().enumerate() {
1809 if i > 0 {
1810 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1811 }
1812 UpperExp::fmt(elem, f)?;
1813 }
1814 if f.alternate() {
1815 write!(f, ",\n")?;
1816 }
1817 write!(f, "]")
1818 }
1819}
1820
1821impl<A: Array> UpperHex for ArrayVec<A>
1822where
1823 A::Item: UpperHex,
1824{
1825 #[allow(clippy::missing_inline_in_public_items)]
1826 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1827 write!(f, "[")?;
1828 if f.alternate() {
1829 write!(f, "\n ")?;
1830 }
1831 for (i, elem) in self.iter().enumerate() {
1832 if i > 0 {
1833 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1834 }
1835 UpperHex::fmt(elem, f)?;
1836 }
1837 if f.alternate() {
1838 write!(f, ",\n")?;
1839 }
1840 write!(f, "]")
1841 }
1842}
1843
1844#[cfg(feature = "alloc")]
1845use alloc::vec::Vec;
1846
1847#[cfg(all(feature = "alloc", feature = "rustc_1_57"))]
1848use alloc::collections::TryReserveError;
1849
1850#[cfg(feature = "alloc")]
1851impl<A: Array> ArrayVec<A> {
1852 pub fn drain_to_vec_and_reserve(&mut self, n: usize) -> Vec<A::Item> {
1861 let cap = n + self.len();
1862 let mut v = Vec::with_capacity(cap);
1863 let iter = self.iter_mut().map(core::mem::take);
1864 v.extend(iter);
1865 self.set_len(0);
1866 return v;
1867 }
1868
1869 #[cfg(feature = "rustc_1_57")]
1885 pub fn try_drain_to_vec_and_reserve(
1886 &mut self, n: usize,
1887 ) -> Result<Vec<A::Item>, TryReserveError> {
1888 let cap = n + self.len();
1889 let mut v = Vec::new();
1890 v.try_reserve(cap)?;
1891 let iter = self.iter_mut().map(core::mem::take);
1892 v.extend(iter);
1893 self.set_len(0);
1894 return Ok(v);
1895 }
1896
1897 pub fn drain_to_vec(&mut self) -> Vec<A::Item> {
1906 self.drain_to_vec_and_reserve(0)
1907 }
1908
1909 #[cfg(feature = "rustc_1_57")]
1926 pub fn try_drain_to_vec(&mut self) -> Result<Vec<A::Item>, TryReserveError> {
1927 self.try_drain_to_vec_and_reserve(0)
1928 }
1929}
1930
1931#[cfg(feature = "serde")]
1932struct ArrayVecVisitor<A: Array>(PhantomData<A>);
1933
1934#[cfg(feature = "serde")]
1935impl<'de, A: Array> Visitor<'de> for ArrayVecVisitor<A>
1936where
1937 A::Item: Deserialize<'de>,
1938{
1939 type Value = ArrayVec<A>;
1940
1941 fn expecting(
1942 &self, formatter: &mut core::fmt::Formatter,
1943 ) -> core::fmt::Result {
1944 formatter.write_str("a sequence")
1945 }
1946
1947 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
1948 where
1949 S: SeqAccess<'de>,
1950 {
1951 let mut new_arrayvec: ArrayVec<A> = Default::default();
1952
1953 let mut idx = 0usize;
1954 while let Some(value) = seq.next_element()? {
1955 if new_arrayvec.len() >= new_arrayvec.capacity() {
1956 return Err(DeserializeError::invalid_length(idx, &self));
1957 }
1958 new_arrayvec.push(value);
1959 idx = idx + 1;
1960 }
1961
1962 Ok(new_arrayvec)
1963 }
1964}
1965
1966#[cfg(test)]
1967mod test {
1968 use super::*;
1969
1970 #[test]
1971 fn retain_mut_empty_vec() {
1972 let mut av: ArrayVec<[i32; 4]> = ArrayVec::new();
1973 av.retain_mut(|&mut x| x % 2 == 0);
1974 assert_eq!(av.len(), 0);
1975 }
1976
1977 #[test]
1978 fn retain_mut_all_elements() {
1979 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 2, 4, 6, 8);
1980 av.retain_mut(|&mut x| x % 2 == 0);
1981 assert_eq!(av.len(), 4);
1982 assert_eq!(av.as_slice(), &[2, 4, 6, 8]);
1983 }
1984
1985 #[test]
1986 fn retain_mut_some_elements() {
1987 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 2, 3, 4);
1988 av.retain_mut(|&mut x| x % 2 == 0);
1989 assert_eq!(av.len(), 2);
1990 assert_eq!(av.as_slice(), &[2, 4]);
1991 }
1992
1993 #[test]
1994 fn retain_mut_no_elements() {
1995 let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 3, 5, 7);
1996 av.retain_mut(|&mut x| x % 2 == 0);
1997 assert_eq!(av.len(), 0);
1998 }
1999
2000 #[test]
2001 fn retain_mut_zero_capacity() {
2002 let mut av: ArrayVec<[i32; 0]> = ArrayVec::new();
2003 av.retain_mut(|&mut x| x % 2 == 0);
2004 assert_eq!(av.len(), 0);
2005 }
2006}