1 use super::*; 2 use core::convert::TryInto; 3 4 #[cfg(feature = "serde")] 5 use core::marker::PhantomData; 6 #[cfg(feature = "serde")] 7 use serde::de::{ 8 Deserialize, Deserializer, Error as DeserializeError, SeqAccess, Visitor, 9 }; 10 #[cfg(feature = "serde")] 11 use serde::ser::{Serialize, SerializeSeq, Serializer}; 12 13 /// Helper to make an `ArrayVec`. 14 /// 15 /// You specify the backing array type, and optionally give all the elements you 16 /// want to initially place into the array. 17 /// 18 /// ```rust 19 /// use tinyvec::*; 20 /// 21 /// // The backing array type can be specified in the macro call 22 /// let empty_av = array_vec!([u8; 16]); 23 /// let some_ints = array_vec!([i32; 4] => 1, 2, 3); 24 /// 25 /// // Or left to inference 26 /// let empty_av: ArrayVec<[u8; 10]> = array_vec!(); 27 /// let some_ints: ArrayVec<[u8; 10]> = array_vec!(5, 6, 7, 8); 28 /// ``` 29 #[macro_export] 30 macro_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 /// An array-backed, vector-like data structure. 53 /// 54 /// * `ArrayVec` has a fixed capacity, equal to the array size. 55 /// * `ArrayVec` has a variable length, as you add and remove elements. Attempts 56 /// to fill the vec beyond its capacity will cause a panic. 57 /// * All of the vec's array slots are always initialized in terms of Rust's 58 /// memory model. When you remove a element from a location, the old value at 59 /// that location is replaced with the type's default value. 60 /// 61 /// The overall API of this type is intended to, as much as possible, emulate 62 /// the API of the [`Vec`](https://doc.rust-lang.org/alloc/vec/struct.Vec.html) 63 /// type. 64 /// 65 /// ## Construction 66 /// 67 /// You can use the `array_vec!` macro similarly to how you might use the `vec!` 68 /// macro. Specify the array type, then optionally give all the initial values 69 /// you want to have. 70 /// ```rust 71 /// # use tinyvec::*; 72 /// let some_ints = array_vec!([i32; 4] => 1, 2, 3); 73 /// assert_eq!(some_ints.len(), 3); 74 /// ``` 75 /// 76 /// The [`default`](ArrayVec::new) for an `ArrayVec` is to have a default 77 /// array with length 0. The [`new`](ArrayVec::new) method is the same as 78 /// calling `default` 79 /// ```rust 80 /// # use tinyvec::*; 81 /// let some_ints = ArrayVec::<[i32; 7]>::default(); 82 /// assert_eq!(some_ints.len(), 0); 83 /// 84 /// let more_ints = ArrayVec::<[i32; 7]>::new(); 85 /// assert_eq!(some_ints, more_ints); 86 /// ``` 87 /// 88 /// If you have an array and want the _whole thing_ so count as being "in" the 89 /// new `ArrayVec` you can use one of the `from` implementations. If you want 90 /// _part of_ the array then you can use 91 /// [`from_array_len`](ArrayVec::from_array_len): 92 /// ```rust 93 /// # use tinyvec::*; 94 /// let some_ints = ArrayVec::from([5, 6, 7, 8]); 95 /// assert_eq!(some_ints.len(), 4); 96 /// 97 /// let more_ints = ArrayVec::from_array_len([5, 6, 7, 8], 2); 98 /// assert_eq!(more_ints.len(), 2); 99 /// ``` 100 #[repr(C)] 101 #[derive(Clone, Copy)] 102 pub struct ArrayVec<A: Array> { 103 len: u16, 104 pub(crate) data: A, 105 } 106 107 impl<A: Array> Default for ArrayVec<A> { default() -> Self108 fn default() -> Self { 109 Self { len: 0, data: A::default() } 110 } 111 } 112 113 impl<A: Array> Deref for ArrayVec<A> { 114 type Target = [A::Item]; 115 #[inline(always)] 116 #[must_use] deref(&self) -> &Self::Target117 fn deref(&self) -> &Self::Target { 118 &self.data.as_slice()[..self.len as usize] 119 } 120 } 121 122 impl<A: Array> DerefMut for ArrayVec<A> { 123 #[inline(always)] 124 #[must_use] deref_mut(&mut self) -> &mut Self::Target125 fn deref_mut(&mut self) -> &mut Self::Target { 126 &mut self.data.as_slice_mut()[..self.len as usize] 127 } 128 } 129 130 impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for ArrayVec<A> { 131 type Output = <I as SliceIndex<[A::Item]>>::Output; 132 #[inline(always)] 133 #[must_use] index(&self, index: I) -> &Self::Output134 fn index(&self, index: I) -> &Self::Output { 135 &self.deref()[index] 136 } 137 } 138 139 impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for ArrayVec<A> { 140 #[inline(always)] 141 #[must_use] index_mut(&mut self, index: I) -> &mut Self::Output142 fn index_mut(&mut self, index: I) -> &mut Self::Output { 143 &mut self.deref_mut()[index] 144 } 145 } 146 147 #[cfg(feature = "serde")] 148 #[cfg_attr(docs_rs, doc(cfg(feature = "serde")))] 149 impl<A: Array> Serialize for ArrayVec<A> 150 where 151 A::Item: Serialize, 152 { 153 #[must_use] serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,154 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 155 where 156 S: Serializer, 157 { 158 let mut seq = serializer.serialize_seq(Some(self.len()))?; 159 for element in self.iter() { 160 seq.serialize_element(element)?; 161 } 162 seq.end() 163 } 164 } 165 166 #[cfg(feature = "serde")] 167 #[cfg_attr(docs_rs, doc(cfg(feature = "serde")))] 168 impl<'de, A: Array> Deserialize<'de> for ArrayVec<A> 169 where 170 A::Item: Deserialize<'de>, 171 { deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,172 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 173 where 174 D: Deserializer<'de>, 175 { 176 deserializer.deserialize_seq(ArrayVecVisitor(PhantomData)) 177 } 178 } 179 180 impl<A: Array> ArrayVec<A> { 181 /// Move all values from `other` into this vec. 182 /// 183 /// ## Panics 184 /// * If the vec overflows its capacity 185 /// 186 /// ## Example 187 /// ```rust 188 /// # use tinyvec::*; 189 /// let mut av = array_vec!([i32; 10] => 1, 2, 3); 190 /// let mut av2 = array_vec!([i32; 10] => 4, 5, 6); 191 /// av.append(&mut av2); 192 /// assert_eq!(av, &[1, 2, 3, 4, 5, 6][..]); 193 /// assert_eq!(av2, &[][..]); 194 /// ``` 195 #[inline] append(&mut self, other: &mut Self)196 pub fn append(&mut self, other: &mut Self) { 197 assert!( 198 self.try_append(other).is_none(), 199 "ArrayVec::append> total length {} exceeds capacity {}!", 200 self.len() + other.len(), 201 A::CAPACITY 202 ); 203 } 204 205 /// Move all values from `other` into this vec. 206 /// If appending would overflow the capacity, Some(other) is returned. 207 /// ## Example 208 /// ```rust 209 /// # use tinyvec::*; 210 /// let mut av = array_vec!([i32; 7] => 1, 2, 3); 211 /// let mut av2 = array_vec!([i32; 7] => 4, 5, 6); 212 /// av.append(&mut av2); 213 /// assert_eq!(av, &[1, 2, 3, 4, 5, 6][..]); 214 /// assert_eq!(av2, &[][..]); 215 /// 216 /// let mut av3 = array_vec!([i32; 7] => 7, 8, 9); 217 /// assert!(av.try_append(&mut av3).is_some()); 218 /// assert_eq!(av, &[1, 2, 3, 4, 5, 6][..]); 219 /// assert_eq!(av3, &[7, 8, 9][..]); 220 /// ``` 221 #[inline] try_append<'other>( &mut self, other: &'other mut Self, ) -> Option<&'other mut Self>222 pub fn try_append<'other>( 223 &mut self, other: &'other mut Self, 224 ) -> Option<&'other mut Self> { 225 let new_len = self.len() + other.len(); 226 if new_len > A::CAPACITY { 227 return Some(other); 228 } 229 230 let iter = other.iter_mut().map(take); 231 for item in iter { 232 self.push(item); 233 } 234 235 other.set_len(0); 236 237 return None; 238 } 239 240 /// A `*mut` pointer to the backing array. 241 /// 242 /// ## Safety 243 /// 244 /// This pointer has provenance over the _entire_ backing array. 245 #[inline(always)] 246 #[must_use] as_mut_ptr(&mut self) -> *mut A::Item247 pub fn as_mut_ptr(&mut self) -> *mut A::Item { 248 self.data.as_slice_mut().as_mut_ptr() 249 } 250 251 /// Performs a `deref_mut`, into unique slice form. 252 #[inline(always)] 253 #[must_use] as_mut_slice(&mut self) -> &mut [A::Item]254 pub fn as_mut_slice(&mut self) -> &mut [A::Item] { 255 self.deref_mut() 256 } 257 258 /// A `*const` pointer to the backing array. 259 /// 260 /// ## Safety 261 /// 262 /// This pointer has provenance over the _entire_ backing array. 263 #[inline(always)] 264 #[must_use] as_ptr(&self) -> *const A::Item265 pub fn as_ptr(&self) -> *const A::Item { 266 self.data.as_slice().as_ptr() 267 } 268 269 /// Performs a `deref`, into shared slice form. 270 #[inline(always)] 271 #[must_use] as_slice(&self) -> &[A::Item]272 pub fn as_slice(&self) -> &[A::Item] { 273 self.deref() 274 } 275 276 /// The capacity of the `ArrayVec`. 277 /// 278 /// This is fixed based on the array type, but can't yet be made a `const fn` 279 /// on Stable Rust. 280 #[inline(always)] 281 #[must_use] capacity(&self) -> usize282 pub fn capacity(&self) -> usize { 283 // Note: This shouldn't use A::CAPACITY, because unsafe code can't rely on 284 // any Array invariants. This ensures that at the very least, the returned 285 // value is a valid length for a subslice of the backing array. 286 self.data.as_slice().len() 287 } 288 289 /// Truncates the `ArrayVec` down to length 0. 290 #[inline(always)] clear(&mut self)291 pub fn clear(&mut self) { 292 self.truncate(0) 293 } 294 295 /// Creates a draining iterator that removes the specified range in the vector 296 /// and yields the removed items. 297 /// 298 /// ## Panics 299 /// * If the start is greater than the end 300 /// * If the end is past the edge of the vec. 301 /// 302 /// ## Example 303 /// ```rust 304 /// # use tinyvec::*; 305 /// let mut av = array_vec!([i32; 4] => 1, 2, 3); 306 /// let av2: ArrayVec<[i32; 4]> = av.drain(1..).collect(); 307 /// assert_eq!(av.as_slice(), &[1][..]); 308 /// assert_eq!(av2.as_slice(), &[2, 3][..]); 309 /// 310 /// av.drain(..); 311 /// assert_eq!(av.as_slice(), &[]); 312 /// ``` 313 #[inline] drain<R>(&mut self, range: R) -> ArrayVecDrain<'_, A::Item> where R: RangeBounds<usize>,314 pub fn drain<R>(&mut self, range: R) -> ArrayVecDrain<'_, A::Item> 315 where 316 R: RangeBounds<usize>, 317 { 318 ArrayVecDrain::new(self, range) 319 } 320 321 /// Returns the inner array of the `ArrayVec`. 322 /// 323 /// This returns the full array, even if the `ArrayVec` length is currently 324 /// less than that. 325 /// 326 /// ## Example 327 /// 328 /// ```rust 329 /// # use tinyvec::{array_vec, ArrayVec}; 330 /// let mut favorite_numbers = array_vec!([i32; 5] => 87, 48, 33, 9, 26); 331 /// assert_eq!(favorite_numbers.clone().into_inner(), [87, 48, 33, 9, 26]); 332 /// 333 /// favorite_numbers.pop(); 334 /// assert_eq!(favorite_numbers.into_inner(), [87, 48, 33, 9, 0]); 335 /// ``` 336 /// 337 /// A use for this function is to build an array from an iterator by first 338 /// collecting it into an `ArrayVec`. 339 /// 340 /// ```rust 341 /// # use tinyvec::ArrayVec; 342 /// let arr_vec: ArrayVec<[i32; 10]> = (1..=3).cycle().take(10).collect(); 343 /// let inner = arr_vec.into_inner(); 344 /// assert_eq!(inner, [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]); 345 /// ``` 346 #[inline] into_inner(self) -> A347 pub fn into_inner(self) -> A { 348 self.data 349 } 350 351 /// Clone each element of the slice into this `ArrayVec`. 352 /// 353 /// ## Panics 354 /// * If the `ArrayVec` would overflow, this will panic. 355 #[inline] extend_from_slice(&mut self, sli: &[A::Item]) where A::Item: Clone,356 pub fn extend_from_slice(&mut self, sli: &[A::Item]) 357 where 358 A::Item: Clone, 359 { 360 if sli.is_empty() { 361 return; 362 } 363 364 let new_len = self.len as usize + sli.len(); 365 assert!( 366 new_len <= A::CAPACITY, 367 "ArrayVec::extend_from_slice> total length {} exceeds capacity {}!", 368 new_len, 369 A::CAPACITY 370 ); 371 372 let target = &mut self.data.as_slice_mut()[self.len as usize..new_len]; 373 target.clone_from_slice(sli); 374 self.set_len(new_len); 375 } 376 377 /// Fill the vector until its capacity has been reached. 378 /// 379 /// Successively fills unused space in the spare slice of the vector with 380 /// elements from the iterator. It then returns the remaining iterator 381 /// without exhausting it. This also allows appending the head of an 382 /// infinite iterator. 383 /// 384 /// This is an alternative to `Extend::extend` method for cases where the 385 /// length of the iterator can not be checked. Since this vector can not 386 /// reallocate to increase its capacity, it is unclear what to do with 387 /// remaining elements in the iterator and the iterator itself. The 388 /// interface also provides no way to communicate this to the caller. 389 /// 390 /// ## Panics 391 /// * If the `next` method of the provided iterator panics. 392 /// 393 /// ## Example 394 /// 395 /// ```rust 396 /// # use tinyvec::*; 397 /// let mut av = array_vec!([i32; 4]); 398 /// let mut to_inf = av.fill(0..); 399 /// assert_eq!(&av[..], [0, 1, 2, 3]); 400 /// assert_eq!(to_inf.next(), Some(4)); 401 /// ``` 402 #[inline] fill<I: IntoIterator<Item = A::Item>>( &mut self, iter: I, ) -> I::IntoIter403 pub fn fill<I: IntoIterator<Item = A::Item>>( 404 &mut self, iter: I, 405 ) -> I::IntoIter { 406 // If this is written as a call to push for each element in iter, the 407 // compiler emits code that updates the length for every element. The 408 // additional complexity from that length update is worth nearly 2x in 409 // the runtime of this function. 410 let mut iter = iter.into_iter(); 411 let mut pushed = 0; 412 let to_take = self.capacity() - self.len(); 413 let target = &mut self.data.as_slice_mut()[self.len as usize..]; 414 for element in iter.by_ref().take(to_take) { 415 target[pushed] = element; 416 pushed += 1; 417 } 418 self.len += pushed as u16; 419 iter 420 } 421 422 /// Wraps up an array and uses the given length as the initial length. 423 /// 424 /// If you want to simply use the full array, use `from` instead. 425 /// 426 /// ## Panics 427 /// 428 /// * The length specified must be less than or equal to the capacity of the 429 /// array. 430 #[inline] 431 #[must_use] 432 #[allow(clippy::match_wild_err_arm)] from_array_len(data: A, len: usize) -> Self433 pub fn from_array_len(data: A, len: usize) -> Self { 434 match Self::try_from_array_len(data, len) { 435 Ok(out) => out, 436 Err(_) => panic!( 437 "ArrayVec::from_array_len> length {} exceeds capacity {}!", 438 len, 439 A::CAPACITY 440 ), 441 } 442 } 443 444 /// Inserts an item at the position given, moving all following elements +1 445 /// index. 446 /// 447 /// ## Panics 448 /// * If `index` > `len` 449 /// * If the capacity is exhausted 450 /// 451 /// ## Example 452 /// ```rust 453 /// use tinyvec::*; 454 /// let mut av = array_vec!([i32; 10] => 1, 2, 3); 455 /// av.insert(1, 4); 456 /// assert_eq!(av.as_slice(), &[1, 4, 2, 3]); 457 /// av.insert(4, 5); 458 /// assert_eq!(av.as_slice(), &[1, 4, 2, 3, 5]); 459 /// ``` 460 #[inline] insert(&mut self, index: usize, item: A::Item)461 pub fn insert(&mut self, index: usize, item: A::Item) { 462 let x = self.try_insert(index, item); 463 assert!(x.is_none(), "ArrayVec::insert> capacity overflow!"); 464 } 465 466 /// Tries to insert an item at the position given, moving all following 467 /// elements +1 index. 468 /// Returns back the element if the capacity is exhausted, 469 /// otherwise returns None. 470 /// 471 /// ## Panics 472 /// * If `index` > `len` 473 /// 474 /// ## Example 475 /// ```rust 476 /// use tinyvec::*; 477 /// let mut av = array_vec!([&'static str; 4] => "one", "two", "three"); 478 /// av.insert(1, "four"); 479 /// assert_eq!(av.as_slice(), &["one", "four", "two", "three"]); 480 /// assert_eq!(av.try_insert(4, "five"), Some("five")); 481 /// ``` 482 #[inline] try_insert( &mut self, index: usize, mut item: A::Item, ) -> Option<A::Item>483 pub fn try_insert( 484 &mut self, index: usize, mut item: A::Item, 485 ) -> Option<A::Item> { 486 assert!( 487 index <= self.len as usize, 488 "ArrayVec::try_insert> index {} is out of bounds {}", 489 index, 490 self.len 491 ); 492 493 // A previous implementation used self.try_push and slice::rotate_right 494 // rotate_right and rotate_left generate a huge amount of code and fail to 495 // inline; calling them here incurs the cost of all the cases they 496 // handle even though we're rotating a usually-small array by a constant 497 // 1 offset. This swap-based implementation benchmarks much better for 498 // small array lengths in particular. 499 500 if (self.len as usize) < A::CAPACITY { 501 self.len += 1; 502 } else { 503 return Some(item); 504 } 505 506 let target = &mut self.as_mut_slice()[index..]; 507 for i in 0..target.len() { 508 core::mem::swap(&mut item, &mut target[i]); 509 } 510 return None; 511 } 512 513 /// Checks if the length is 0. 514 #[inline(always)] 515 #[must_use] is_empty(&self) -> bool516 pub fn is_empty(&self) -> bool { 517 self.len == 0 518 } 519 520 /// The length of the `ArrayVec` (in elements). 521 #[inline(always)] 522 #[must_use] len(&self) -> usize523 pub fn len(&self) -> usize { 524 self.len as usize 525 } 526 527 /// Makes a new, empty `ArrayVec`. 528 #[inline(always)] 529 #[must_use] new() -> Self530 pub fn new() -> Self { 531 Self::default() 532 } 533 534 /// Remove and return the last element of the vec, if there is one. 535 /// 536 /// ## Failure 537 /// * If the vec is empty you get `None`. 538 /// 539 /// ## Example 540 /// ```rust 541 /// # use tinyvec::*; 542 /// let mut av = array_vec!([i32; 10] => 1, 2); 543 /// assert_eq!(av.pop(), Some(2)); 544 /// assert_eq!(av.pop(), Some(1)); 545 /// assert_eq!(av.pop(), None); 546 /// ``` 547 #[inline] pop(&mut self) -> Option<A::Item>548 pub fn pop(&mut self) -> Option<A::Item> { 549 if self.len > 0 { 550 self.len -= 1; 551 let out = take(&mut self.data.as_slice_mut()[self.len as usize]); 552 Some(out) 553 } else { 554 None 555 } 556 } 557 558 /// Place an element onto the end of the vec. 559 /// 560 /// ## Panics 561 /// * If the length of the vec would overflow the capacity. 562 /// 563 /// ## Example 564 /// ```rust 565 /// # use tinyvec::*; 566 /// let mut av = array_vec!([i32; 2]); 567 /// assert_eq!(&av[..], []); 568 /// av.push(1); 569 /// assert_eq!(&av[..], [1]); 570 /// av.push(2); 571 /// assert_eq!(&av[..], [1, 2]); 572 /// // av.push(3); this would overflow the ArrayVec and panic! 573 /// ``` 574 #[inline(always)] push(&mut self, val: A::Item)575 pub fn push(&mut self, val: A::Item) { 576 let x = self.try_push(val); 577 assert!(x.is_none(), "ArrayVec::push> capacity overflow!"); 578 } 579 580 /// Tries to place an element onto the end of the vec.\ 581 /// Returns back the element if the capacity is exhausted, 582 /// otherwise returns None. 583 /// ```rust 584 /// # use tinyvec::*; 585 /// let mut av = array_vec!([i32; 2]); 586 /// assert_eq!(av.as_slice(), []); 587 /// assert_eq!(av.try_push(1), None); 588 /// assert_eq!(&av[..], [1]); 589 /// assert_eq!(av.try_push(2), None); 590 /// assert_eq!(&av[..], [1, 2]); 591 /// assert_eq!(av.try_push(3), Some(3)); 592 /// ``` 593 #[inline(always)] try_push(&mut self, val: A::Item) -> Option<A::Item>594 pub fn try_push(&mut self, val: A::Item) -> Option<A::Item> { 595 debug_assert!(self.len as usize <= A::CAPACITY); 596 597 let itemref = match self.data.as_slice_mut().get_mut(self.len as usize) { 598 None => return Some(val), 599 Some(x) => x, 600 }; 601 602 *itemref = val; 603 self.len += 1; 604 return None; 605 } 606 607 /// Removes the item at `index`, shifting all others down by one index. 608 /// 609 /// Returns the removed element. 610 /// 611 /// ## Panics 612 /// 613 /// * If the index is out of bounds. 614 /// 615 /// ## Example 616 /// 617 /// ```rust 618 /// # use tinyvec::*; 619 /// let mut av = array_vec!([i32; 4] => 1, 2, 3); 620 /// assert_eq!(av.remove(1), 2); 621 /// assert_eq!(&av[..], [1, 3]); 622 /// ``` 623 #[inline] remove(&mut self, index: usize) -> A::Item624 pub fn remove(&mut self, index: usize) -> A::Item { 625 let targets: &mut [A::Item] = &mut self.deref_mut()[index..]; 626 let item = take(&mut targets[0]); 627 628 // A previous implementation used rotate_left 629 // rotate_right and rotate_left generate a huge amount of code and fail to 630 // inline; calling them here incurs the cost of all the cases they 631 // handle even though we're rotating a usually-small array by a constant 632 // 1 offset. This swap-based implementation benchmarks much better for 633 // small array lengths in particular. 634 635 for i in 0..targets.len() - 1 { 636 targets.swap(i, i + 1); 637 } 638 self.len -= 1; 639 item 640 } 641 642 /// As [`resize_with`](ArrayVec::resize_with) 643 /// and it clones the value as the closure. 644 /// 645 /// ## Example 646 /// 647 /// ```rust 648 /// # use tinyvec::*; 649 /// 650 /// let mut av = array_vec!([&str; 10] => "hello"); 651 /// av.resize(3, "world"); 652 /// assert_eq!(&av[..], ["hello", "world", "world"]); 653 /// 654 /// let mut av = array_vec!([i32; 10] => 1, 2, 3, 4); 655 /// av.resize(2, 0); 656 /// assert_eq!(&av[..], [1, 2]); 657 /// ``` 658 #[inline] resize(&mut self, new_len: usize, new_val: A::Item) where A::Item: Clone,659 pub fn resize(&mut self, new_len: usize, new_val: A::Item) 660 where 661 A::Item: Clone, 662 { 663 self.resize_with(new_len, || new_val.clone()) 664 } 665 666 /// Resize the vec to the new length. 667 /// 668 /// If it needs to be longer, it's filled with repeated calls to the provided 669 /// function. If it needs to be shorter, it's truncated. 670 /// 671 /// ## Example 672 /// 673 /// ```rust 674 /// # use tinyvec::*; 675 /// 676 /// let mut av = array_vec!([i32; 10] => 1, 2, 3); 677 /// av.resize_with(5, Default::default); 678 /// assert_eq!(&av[..], [1, 2, 3, 0, 0]); 679 /// 680 /// let mut av = array_vec!([i32; 10]); 681 /// let mut p = 1; 682 /// av.resize_with(4, || { 683 /// p *= 2; 684 /// p 685 /// }); 686 /// assert_eq!(&av[..], [2, 4, 8, 16]); 687 /// ``` 688 #[inline] resize_with<F: FnMut() -> A::Item>( &mut self, new_len: usize, mut f: F, )689 pub fn resize_with<F: FnMut() -> A::Item>( 690 &mut self, new_len: usize, mut f: F, 691 ) { 692 match new_len.checked_sub(self.len as usize) { 693 None => self.truncate(new_len), 694 Some(new_elements) => { 695 for _ in 0..new_elements { 696 self.push(f()); 697 } 698 } 699 } 700 } 701 702 /// Walk the vec and keep only the elements that pass the predicate given. 703 /// 704 /// ## Example 705 /// 706 /// ```rust 707 /// # use tinyvec::*; 708 /// 709 /// let mut av = array_vec!([i32; 10] => 1, 1, 2, 3, 3, 4); 710 /// av.retain(|&x| x % 2 == 0); 711 /// assert_eq!(&av[..], [2, 4]); 712 /// ``` 713 #[inline] retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F)714 pub fn retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F) { 715 // Drop guard to contain exactly the remaining elements when the test 716 // panics. 717 struct JoinOnDrop<'vec, Item> { 718 items: &'vec mut [Item], 719 done_end: usize, 720 // Start of tail relative to `done_end`. 721 tail_start: usize, 722 } 723 724 impl<Item> Drop for JoinOnDrop<'_, Item> { 725 fn drop(&mut self) { 726 self.items[self.done_end..].rotate_left(self.tail_start); 727 } 728 } 729 730 let mut rest = JoinOnDrop { 731 items: &mut self.data.as_slice_mut()[..self.len as usize], 732 done_end: 0, 733 tail_start: 0, 734 }; 735 736 let len = self.len as usize; 737 for idx in 0..len { 738 // Loop start invariant: idx = rest.done_end + rest.tail_start 739 if !acceptable(&rest.items[idx]) { 740 let _ = take(&mut rest.items[idx]); 741 self.len -= 1; 742 rest.tail_start += 1; 743 } else { 744 rest.items.swap(rest.done_end, idx); 745 rest.done_end += 1; 746 } 747 } 748 } 749 750 /// Forces the length of the vector to `new_len`. 751 /// 752 /// ## Panics 753 /// * If `new_len` is greater than the vec's capacity. 754 /// 755 /// ## Safety 756 /// * This is a fully safe operation! The inactive memory already counts as 757 /// "initialized" by Rust's rules. 758 /// * Other than "the memory is initialized" there are no other guarantees 759 /// regarding what you find in the inactive portion of the vec. 760 #[inline(always)] set_len(&mut self, new_len: usize)761 pub fn set_len(&mut self, new_len: usize) { 762 if new_len > A::CAPACITY { 763 // Note(Lokathor): Technically we don't have to panic here, and we could 764 // just let some other call later on trigger a panic on accident when the 765 // length is wrong. However, it's a lot easier to catch bugs when things 766 // are more "fail-fast". 767 panic!( 768 "ArrayVec::set_len> new length {} exceeds capacity {}", 769 new_len, 770 A::CAPACITY 771 ) 772 } 773 774 let new_len: u16 = new_len 775 .try_into() 776 .expect("ArrayVec::set_len> new length is not in range 0..=u16::MAX"); 777 self.len = new_len; 778 } 779 780 /// Splits the collection at the point given. 781 /// 782 /// * `[0, at)` stays in this vec 783 /// * `[at, len)` ends up in the new vec. 784 /// 785 /// ## Panics 786 /// * if at > len 787 /// 788 /// ## Example 789 /// 790 /// ```rust 791 /// # use tinyvec::*; 792 /// let mut av = array_vec!([i32; 4] => 1, 2, 3); 793 /// let av2 = av.split_off(1); 794 /// assert_eq!(&av[..], [1]); 795 /// assert_eq!(&av2[..], [2, 3]); 796 /// ``` 797 #[inline] split_off(&mut self, at: usize) -> Self798 pub fn split_off(&mut self, at: usize) -> Self { 799 // FIXME: should this just use drain into the output? 800 if at > self.len() { 801 panic!( 802 "ArrayVec::split_off> at value {} exceeds length of {}", 803 at, self.len 804 ); 805 } 806 let mut new = Self::default(); 807 let moves = &mut self.as_mut_slice()[at..]; 808 let split_len = moves.len(); 809 let targets = &mut new.data.as_slice_mut()[..split_len]; 810 moves.swap_with_slice(targets); 811 812 /* moves.len() <= u16::MAX, so these are surely in u16 range */ 813 new.len = split_len as u16; 814 self.len = at as u16; 815 new 816 } 817 818 /// Creates a splicing iterator that removes the specified range in the 819 /// vector, yields the removed items, and replaces them with elements from 820 /// the provided iterator. 821 /// 822 /// `splice` fuses the provided iterator, so elements after the first `None` 823 /// are ignored. 824 /// 825 /// ## Panics 826 /// * If the start is greater than the end. 827 /// * If the end is past the edge of the vec. 828 /// * If the provided iterator panics. 829 /// * If the new length would overflow the capacity of the array. Because 830 /// `ArrayVecSplice` adds elements to this vec in its destructor when 831 /// necessary, this panic would occur when it is dropped. 832 /// 833 /// ## Example 834 /// ```rust 835 /// use tinyvec::*; 836 /// let mut av = array_vec!([i32; 4] => 1, 2, 3); 837 /// let av2: ArrayVec<[i32; 4]> = av.splice(1.., 4..=6).collect(); 838 /// assert_eq!(av.as_slice(), &[1, 4, 5, 6][..]); 839 /// assert_eq!(av2.as_slice(), &[2, 3][..]); 840 /// 841 /// av.splice(.., None); 842 /// assert_eq!(av.as_slice(), &[]); 843 /// ``` 844 #[inline] splice<R, I>( &mut self, range: R, replacement: I, ) -> ArrayVecSplice<'_, A, core::iter::Fuse<I::IntoIter>> where R: RangeBounds<usize>, I: IntoIterator<Item = A::Item>,845 pub fn splice<R, I>( 846 &mut self, range: R, replacement: I, 847 ) -> ArrayVecSplice<'_, A, core::iter::Fuse<I::IntoIter>> 848 where 849 R: RangeBounds<usize>, 850 I: IntoIterator<Item = A::Item>, 851 { 852 use core::ops::Bound; 853 let start = match range.start_bound() { 854 Bound::Included(x) => *x, 855 Bound::Excluded(x) => x.saturating_add(1), 856 Bound::Unbounded => 0, 857 }; 858 let end = match range.end_bound() { 859 Bound::Included(x) => x.saturating_add(1), 860 Bound::Excluded(x) => *x, 861 Bound::Unbounded => self.len(), 862 }; 863 assert!( 864 start <= end, 865 "ArrayVec::splice> Illegal range, {} to {}", 866 start, 867 end 868 ); 869 assert!( 870 end <= self.len(), 871 "ArrayVec::splice> Range ends at {} but length is only {}!", 872 end, 873 self.len() 874 ); 875 876 ArrayVecSplice { 877 removal_start: start, 878 removal_end: end, 879 parent: self, 880 replacement: replacement.into_iter().fuse(), 881 } 882 } 883 884 /// Remove an element, swapping the end of the vec into its place. 885 /// 886 /// ## Panics 887 /// * If the index is out of bounds. 888 /// 889 /// ## Example 890 /// ```rust 891 /// # use tinyvec::*; 892 /// let mut av = array_vec!([&str; 4] => "foo", "bar", "quack", "zap"); 893 /// 894 /// assert_eq!(av.swap_remove(1), "bar"); 895 /// assert_eq!(&av[..], ["foo", "zap", "quack"]); 896 /// 897 /// assert_eq!(av.swap_remove(0), "foo"); 898 /// assert_eq!(&av[..], ["quack", "zap"]); 899 /// ``` 900 #[inline] swap_remove(&mut self, index: usize) -> A::Item901 pub fn swap_remove(&mut self, index: usize) -> A::Item { 902 assert!( 903 index < self.len(), 904 "ArrayVec::swap_remove> index {} is out of bounds {}", 905 index, 906 self.len 907 ); 908 if index == self.len() - 1 { 909 self.pop().unwrap() 910 } else { 911 let i = self.pop().unwrap(); 912 replace(&mut self[index], i) 913 } 914 } 915 916 /// Reduces the vec's length to the given value. 917 /// 918 /// If the vec is already shorter than the input, nothing happens. 919 #[inline] truncate(&mut self, new_len: usize)920 pub fn truncate(&mut self, new_len: usize) { 921 if new_len >= self.len as usize { 922 return; 923 } 924 925 if needs_drop::<A::Item>() { 926 let len = self.len as usize; 927 self.data.as_slice_mut()[new_len..len] 928 .iter_mut() 929 .map(take) 930 .for_each(drop); 931 } 932 933 /* new_len is less than self.len */ 934 self.len = new_len as u16; 935 } 936 937 /// Wraps an array, using the given length as the starting length. 938 /// 939 /// If you want to use the whole length of the array, you can just use the 940 /// `From` impl. 941 /// 942 /// ## Failure 943 /// 944 /// If the given length is greater than the capacity of the array this will 945 /// error, and you'll get the array back in the `Err`. 946 #[inline] try_from_array_len(data: A, len: usize) -> Result<Self, A>947 pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> { 948 /* Note(Soveu): Should we allow A::CAPACITY > u16::MAX for now? */ 949 if len <= A::CAPACITY { 950 Ok(Self { data, len: len as u16 }) 951 } else { 952 Err(data) 953 } 954 } 955 } 956 957 #[cfg(feature = "grab_spare_slice")] 958 impl<A: Array> ArrayVec<A> { 959 /// Obtain the shared slice of the array _after_ the active memory. 960 /// 961 /// ## Example 962 /// ```rust 963 /// # use tinyvec::*; 964 /// let mut av = array_vec!([i32; 4]); 965 /// assert_eq!(av.grab_spare_slice().len(), 4); 966 /// av.push(10); 967 /// av.push(11); 968 /// av.push(12); 969 /// av.push(13); 970 /// assert_eq!(av.grab_spare_slice().len(), 0); 971 /// ``` 972 #[inline(always)] grab_spare_slice(&self) -> &[A::Item]973 pub fn grab_spare_slice(&self) -> &[A::Item] { 974 &self.data.as_slice()[self.len as usize..] 975 } 976 977 /// Obtain the mutable slice of the array _after_ the active memory. 978 /// 979 /// ## Example 980 /// ```rust 981 /// # use tinyvec::*; 982 /// let mut av = array_vec!([i32; 4]); 983 /// assert_eq!(av.grab_spare_slice_mut().len(), 4); 984 /// av.push(10); 985 /// av.push(11); 986 /// assert_eq!(av.grab_spare_slice_mut().len(), 2); 987 /// ``` 988 #[inline(always)] grab_spare_slice_mut(&mut self) -> &mut [A::Item]989 pub fn grab_spare_slice_mut(&mut self) -> &mut [A::Item] { 990 &mut self.data.as_slice_mut()[self.len as usize..] 991 } 992 } 993 994 #[cfg(feature = "nightly_slice_partition_dedup")] 995 impl<A: Array> ArrayVec<A> { 996 /// De-duplicates the vec contents. 997 #[inline(always)] dedup(&mut self) where A::Item: PartialEq,998 pub fn dedup(&mut self) 999 where 1000 A::Item: PartialEq, 1001 { 1002 self.dedup_by(|a, b| a == b) 1003 } 1004 1005 /// De-duplicates the vec according to the predicate given. 1006 #[inline(always)] dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut A::Item, &mut A::Item) -> bool,1007 pub fn dedup_by<F>(&mut self, same_bucket: F) 1008 where 1009 F: FnMut(&mut A::Item, &mut A::Item) -> bool, 1010 { 1011 let len = { 1012 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket); 1013 dedup.len() 1014 }; 1015 self.truncate(len); 1016 } 1017 1018 /// De-duplicates the vec according to the key selector given. 1019 #[inline(always)] dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut A::Item) -> K, K: PartialEq,1020 pub fn dedup_by_key<F, K>(&mut self, mut key: F) 1021 where 1022 F: FnMut(&mut A::Item) -> K, 1023 K: PartialEq, 1024 { 1025 self.dedup_by(|a, b| key(a) == key(b)) 1026 } 1027 } 1028 1029 /// Splicing iterator for `ArrayVec` 1030 /// See [`ArrayVec::splice`](ArrayVec::<A>::splice) 1031 pub struct ArrayVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> { 1032 parent: &'p mut ArrayVec<A>, 1033 removal_start: usize, 1034 removal_end: usize, 1035 replacement: I, 1036 } 1037 1038 impl<'p, A: Array, I: Iterator<Item = A::Item>> Iterator 1039 for ArrayVecSplice<'p, A, I> 1040 { 1041 type Item = A::Item; 1042 1043 #[inline] next(&mut self) -> Option<A::Item>1044 fn next(&mut self) -> Option<A::Item> { 1045 if self.removal_start < self.removal_end { 1046 match self.replacement.next() { 1047 Some(replacement) => { 1048 let removed = core::mem::replace( 1049 &mut self.parent[self.removal_start], 1050 replacement, 1051 ); 1052 self.removal_start += 1; 1053 Some(removed) 1054 } 1055 None => { 1056 let removed = self.parent.remove(self.removal_start); 1057 self.removal_end -= 1; 1058 Some(removed) 1059 } 1060 } 1061 } else { 1062 None 1063 } 1064 } 1065 1066 #[inline] size_hint(&self) -> (usize, Option<usize>)1067 fn size_hint(&self) -> (usize, Option<usize>) { 1068 let len = self.len(); 1069 (len, Some(len)) 1070 } 1071 } 1072 1073 impl<'p, A, I> ExactSizeIterator for ArrayVecSplice<'p, A, I> 1074 where 1075 A: Array, 1076 I: Iterator<Item = A::Item>, 1077 { 1078 #[inline] len(&self) -> usize1079 fn len(&self) -> usize { 1080 self.removal_end - self.removal_start 1081 } 1082 } 1083 1084 impl<'p, A, I> FusedIterator for ArrayVecSplice<'p, A, I> 1085 where 1086 A: Array, 1087 I: Iterator<Item = A::Item>, 1088 { 1089 } 1090 1091 impl<'p, A, I> DoubleEndedIterator for ArrayVecSplice<'p, A, I> 1092 where 1093 A: Array, 1094 I: Iterator<Item = A::Item> + DoubleEndedIterator, 1095 { 1096 #[inline] next_back(&mut self) -> Option<A::Item>1097 fn next_back(&mut self) -> Option<A::Item> { 1098 if self.removal_start < self.removal_end { 1099 match self.replacement.next_back() { 1100 Some(replacement) => { 1101 let removed = core::mem::replace( 1102 &mut self.parent[self.removal_end - 1], 1103 replacement, 1104 ); 1105 self.removal_end -= 1; 1106 Some(removed) 1107 } 1108 None => { 1109 let removed = self.parent.remove(self.removal_end - 1); 1110 self.removal_end -= 1; 1111 Some(removed) 1112 } 1113 } 1114 } else { 1115 None 1116 } 1117 } 1118 } 1119 1120 impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop 1121 for ArrayVecSplice<'p, A, I> 1122 { drop(&mut self)1123 fn drop(&mut self) { 1124 for _ in self.by_ref() {} 1125 1126 // FIXME: reserve lower bound of size_hint 1127 1128 for replacement in self.replacement.by_ref() { 1129 self.parent.insert(self.removal_end, replacement); 1130 self.removal_end += 1; 1131 } 1132 } 1133 } 1134 1135 impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> { 1136 #[inline(always)] 1137 #[must_use] as_mut(&mut self) -> &mut [A::Item]1138 fn as_mut(&mut self) -> &mut [A::Item] { 1139 &mut *self 1140 } 1141 } 1142 1143 impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> { 1144 #[inline(always)] 1145 #[must_use] as_ref(&self) -> &[A::Item]1146 fn as_ref(&self) -> &[A::Item] { 1147 &*self 1148 } 1149 } 1150 1151 impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> { 1152 #[inline(always)] 1153 #[must_use] borrow(&self) -> &[A::Item]1154 fn borrow(&self) -> &[A::Item] { 1155 &*self 1156 } 1157 } 1158 1159 impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> { 1160 #[inline(always)] 1161 #[must_use] borrow_mut(&mut self) -> &mut [A::Item]1162 fn borrow_mut(&mut self) -> &mut [A::Item] { 1163 &mut *self 1164 } 1165 } 1166 1167 impl<A: Array> Extend<A::Item> for ArrayVec<A> { 1168 #[inline] extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T)1169 fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) { 1170 for t in iter { 1171 self.push(t) 1172 } 1173 } 1174 } 1175 1176 impl<A: Array> From<A> for ArrayVec<A> { 1177 #[inline(always)] 1178 #[must_use] 1179 /// The output has a length equal to the full array. 1180 /// 1181 /// If you want to select a length, use 1182 /// [`from_array_len`](ArrayVec::from_array_len) from(data: A) -> Self1183 fn from(data: A) -> Self { 1184 let len: u16 = data 1185 .as_slice() 1186 .len() 1187 .try_into() 1188 .expect("ArrayVec::from> lenght must be in range 0..=u16::MAX"); 1189 Self { len, data } 1190 } 1191 } 1192 1193 impl<A: Array> FromIterator<A::Item> for ArrayVec<A> { 1194 #[inline] 1195 #[must_use] from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self1196 fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self { 1197 let mut av = Self::default(); 1198 for i in iter { 1199 av.push(i) 1200 } 1201 av 1202 } 1203 } 1204 1205 /// Iterator for consuming an `ArrayVec` and returning owned elements. 1206 pub struct ArrayVecIterator<A: Array> { 1207 base: u16, 1208 tail: u16, 1209 data: A, 1210 } 1211 1212 impl<A: Array> ArrayVecIterator<A> { 1213 /// Returns the remaining items of this iterator as a slice. 1214 #[inline] 1215 #[must_use] as_slice(&self) -> &[A::Item]1216 pub fn as_slice(&self) -> &[A::Item] { 1217 &self.data.as_slice()[self.base as usize..self.tail as usize] 1218 } 1219 } 1220 impl<A: Array> FusedIterator for ArrayVecIterator<A> {} 1221 impl<A: Array> Iterator for ArrayVecIterator<A> { 1222 type Item = A::Item; 1223 #[inline] next(&mut self) -> Option<Self::Item>1224 fn next(&mut self) -> Option<Self::Item> { 1225 let slice = 1226 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize]; 1227 let itemref = slice.first_mut()?; 1228 self.base += 1; 1229 return Some(take(itemref)); 1230 } 1231 #[inline(always)] 1232 #[must_use] size_hint(&self) -> (usize, Option<usize>)1233 fn size_hint(&self) -> (usize, Option<usize>) { 1234 let s = self.tail - self.base; 1235 let s = s as usize; 1236 (s, Some(s)) 1237 } 1238 #[inline(always)] count(self) -> usize1239 fn count(self) -> usize { 1240 self.size_hint().0 1241 } 1242 #[inline] last(mut self) -> Option<Self::Item>1243 fn last(mut self) -> Option<Self::Item> { 1244 self.next_back() 1245 } 1246 #[inline] nth(&mut self, n: usize) -> Option<A::Item>1247 fn nth(&mut self, n: usize) -> Option<A::Item> { 1248 let slice = &mut self.data.as_slice_mut(); 1249 let slice = &mut slice[self.base as usize..self.tail as usize]; 1250 1251 if let Some(x) = slice.get_mut(n) { 1252 /* n is in range [0 .. self.tail - self.base) so in u16 range */ 1253 self.base += n as u16 + 1; 1254 return Some(take(x)); 1255 } 1256 1257 self.base = self.tail; 1258 return None; 1259 } 1260 } 1261 1262 impl<A: Array> DoubleEndedIterator for ArrayVecIterator<A> { 1263 #[inline] next_back(&mut self) -> Option<Self::Item>1264 fn next_back(&mut self) -> Option<Self::Item> { 1265 let slice = 1266 &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize]; 1267 let item = slice.last_mut()?; 1268 self.tail -= 1; 1269 return Some(take(item)); 1270 } 1271 #[cfg(feature = "rustc_1_40")] 1272 #[inline] nth_back(&mut self, n: usize) -> Option<Self::Item>1273 fn nth_back(&mut self, n: usize) -> Option<Self::Item> { 1274 let base = self.base as usize; 1275 let tail = self.tail as usize; 1276 let slice = &mut self.data.as_slice_mut()[base..tail]; 1277 let n = n.saturating_add(1); 1278 1279 if let Some(n) = slice.len().checked_sub(n) { 1280 let item = &mut slice[n]; 1281 /* n is in [0..self.tail - self.base] range, so in u16 range */ 1282 self.tail = self.base + n as u16; 1283 return Some(take(item)); 1284 } 1285 1286 self.tail = self.base; 1287 return None; 1288 } 1289 } 1290 1291 impl<A: Array> Debug for ArrayVecIterator<A> 1292 where 1293 A::Item: Debug, 1294 { 1295 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result1296 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { 1297 f.debug_tuple("ArrayVecIterator").field(&self.as_slice()).finish() 1298 } 1299 } 1300 1301 impl<A: Array> IntoIterator for ArrayVec<A> { 1302 type Item = A::Item; 1303 type IntoIter = ArrayVecIterator<A>; 1304 #[inline(always)] 1305 #[must_use] into_iter(self) -> Self::IntoIter1306 fn into_iter(self) -> Self::IntoIter { 1307 ArrayVecIterator { base: 0, tail: self.len, data: self.data } 1308 } 1309 } 1310 1311 impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> { 1312 type Item = &'a mut A::Item; 1313 type IntoIter = core::slice::IterMut<'a, A::Item>; 1314 #[inline(always)] 1315 #[must_use] into_iter(self) -> Self::IntoIter1316 fn into_iter(self) -> Self::IntoIter { 1317 self.iter_mut() 1318 } 1319 } 1320 1321 impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> { 1322 type Item = &'a A::Item; 1323 type IntoIter = core::slice::Iter<'a, A::Item>; 1324 #[inline(always)] 1325 #[must_use] into_iter(self) -> Self::IntoIter1326 fn into_iter(self) -> Self::IntoIter { 1327 self.iter() 1328 } 1329 } 1330 1331 impl<A: Array> PartialEq for ArrayVec<A> 1332 where 1333 A::Item: PartialEq, 1334 { 1335 #[inline] 1336 #[must_use] eq(&self, other: &Self) -> bool1337 fn eq(&self, other: &Self) -> bool { 1338 self.as_slice().eq(other.as_slice()) 1339 } 1340 } 1341 impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq {} 1342 1343 impl<A: Array> PartialOrd for ArrayVec<A> 1344 where 1345 A::Item: PartialOrd, 1346 { 1347 #[inline] 1348 #[must_use] partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering>1349 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { 1350 self.as_slice().partial_cmp(other.as_slice()) 1351 } 1352 } 1353 impl<A: Array> Ord for ArrayVec<A> 1354 where 1355 A::Item: Ord, 1356 { 1357 #[inline] 1358 #[must_use] cmp(&self, other: &Self) -> core::cmp::Ordering1359 fn cmp(&self, other: &Self) -> core::cmp::Ordering { 1360 self.as_slice().cmp(other.as_slice()) 1361 } 1362 } 1363 1364 impl<A: Array> PartialEq<&A> for ArrayVec<A> 1365 where 1366 A::Item: PartialEq, 1367 { 1368 #[inline] 1369 #[must_use] eq(&self, other: &&A) -> bool1370 fn eq(&self, other: &&A) -> bool { 1371 self.as_slice().eq(other.as_slice()) 1372 } 1373 } 1374 1375 impl<A: Array> PartialEq<&[A::Item]> for ArrayVec<A> 1376 where 1377 A::Item: PartialEq, 1378 { 1379 #[inline] 1380 #[must_use] eq(&self, other: &&[A::Item]) -> bool1381 fn eq(&self, other: &&[A::Item]) -> bool { 1382 self.as_slice().eq(*other) 1383 } 1384 } 1385 1386 impl<A: Array> Hash for ArrayVec<A> 1387 where 1388 A::Item: Hash, 1389 { 1390 #[inline] hash<H: Hasher>(&self, state: &mut H)1391 fn hash<H: Hasher>(&self, state: &mut H) { 1392 self.as_slice().hash(state) 1393 } 1394 } 1395 1396 #[cfg(feature = "experimental_write_impl")] 1397 impl<A: Array<Item = u8>> core::fmt::Write for ArrayVec<A> { write_str(&mut self, s: &str) -> core::fmt::Result1398 fn write_str(&mut self, s: &str) -> core::fmt::Result { 1399 let my_len = self.len(); 1400 let str_len = s.as_bytes().len(); 1401 if my_len + str_len <= A::CAPACITY { 1402 let remainder = &mut self.data.as_slice_mut()[my_len..]; 1403 let target = &mut remainder[..str_len]; 1404 target.copy_from_slice(s.as_bytes()); 1405 Ok(()) 1406 } else { 1407 Err(core::fmt::Error) 1408 } 1409 } 1410 } 1411 1412 // // // // // // // // 1413 // Formatting impls 1414 // // // // // // // // 1415 1416 impl<A: Array> Binary for ArrayVec<A> 1417 where 1418 A::Item: Binary, 1419 { 1420 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1421 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1422 write!(f, "[")?; 1423 for (i, elem) in self.iter().enumerate() { 1424 if i > 0 { 1425 write!(f, ", ")?; 1426 } 1427 Binary::fmt(elem, f)?; 1428 } 1429 write!(f, "]") 1430 } 1431 } 1432 1433 impl<A: Array> Debug for ArrayVec<A> 1434 where 1435 A::Item: Debug, 1436 { 1437 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1438 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1439 write!(f, "[")?; 1440 for (i, elem) in self.iter().enumerate() { 1441 if i > 0 { 1442 write!(f, ", ")?; 1443 } 1444 Debug::fmt(elem, f)?; 1445 } 1446 write!(f, "]") 1447 } 1448 } 1449 1450 impl<A: Array> Display for ArrayVec<A> 1451 where 1452 A::Item: Display, 1453 { 1454 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1455 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1456 write!(f, "[")?; 1457 for (i, elem) in self.iter().enumerate() { 1458 if i > 0 { 1459 write!(f, ", ")?; 1460 } 1461 Display::fmt(elem, f)?; 1462 } 1463 write!(f, "]") 1464 } 1465 } 1466 1467 impl<A: Array> LowerExp for ArrayVec<A> 1468 where 1469 A::Item: LowerExp, 1470 { 1471 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1472 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1473 write!(f, "[")?; 1474 for (i, elem) in self.iter().enumerate() { 1475 if i > 0 { 1476 write!(f, ", ")?; 1477 } 1478 LowerExp::fmt(elem, f)?; 1479 } 1480 write!(f, "]") 1481 } 1482 } 1483 1484 impl<A: Array> LowerHex for ArrayVec<A> 1485 where 1486 A::Item: LowerHex, 1487 { 1488 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1489 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1490 write!(f, "[")?; 1491 for (i, elem) in self.iter().enumerate() { 1492 if i > 0 { 1493 write!(f, ", ")?; 1494 } 1495 LowerHex::fmt(elem, f)?; 1496 } 1497 write!(f, "]") 1498 } 1499 } 1500 1501 impl<A: Array> Octal for ArrayVec<A> 1502 where 1503 A::Item: Octal, 1504 { 1505 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1506 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1507 write!(f, "[")?; 1508 for (i, elem) in self.iter().enumerate() { 1509 if i > 0 { 1510 write!(f, ", ")?; 1511 } 1512 Octal::fmt(elem, f)?; 1513 } 1514 write!(f, "]") 1515 } 1516 } 1517 1518 impl<A: Array> Pointer for ArrayVec<A> 1519 where 1520 A::Item: Pointer, 1521 { 1522 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1523 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1524 write!(f, "[")?; 1525 for (i, elem) in self.iter().enumerate() { 1526 if i > 0 { 1527 write!(f, ", ")?; 1528 } 1529 Pointer::fmt(elem, f)?; 1530 } 1531 write!(f, "]") 1532 } 1533 } 1534 1535 impl<A: Array> UpperExp for ArrayVec<A> 1536 where 1537 A::Item: UpperExp, 1538 { 1539 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1540 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1541 write!(f, "[")?; 1542 for (i, elem) in self.iter().enumerate() { 1543 if i > 0 { 1544 write!(f, ", ")?; 1545 } 1546 UpperExp::fmt(elem, f)?; 1547 } 1548 write!(f, "]") 1549 } 1550 } 1551 1552 impl<A: Array> UpperHex for ArrayVec<A> 1553 where 1554 A::Item: UpperHex, 1555 { 1556 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1557 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1558 write!(f, "[")?; 1559 for (i, elem) in self.iter().enumerate() { 1560 if i > 0 { 1561 write!(f, ", ")?; 1562 } 1563 UpperHex::fmt(elem, f)?; 1564 } 1565 write!(f, "]") 1566 } 1567 } 1568 1569 #[cfg(feature = "alloc")] 1570 use alloc::vec::Vec; 1571 1572 #[cfg(feature = "alloc")] 1573 impl<A: Array> ArrayVec<A> { 1574 /// Drains all elements to a Vec, but reserves additional space 1575 /// ``` 1576 /// # use tinyvec::*; 1577 /// let mut av = array_vec!([i32; 7] => 1, 2, 3); 1578 /// let v = av.drain_to_vec_and_reserve(10); 1579 /// assert_eq!(v, &[1, 2, 3]); 1580 /// assert_eq!(v.capacity(), 13); 1581 /// ``` drain_to_vec_and_reserve(&mut self, n: usize) -> Vec<A::Item>1582 pub fn drain_to_vec_and_reserve(&mut self, n: usize) -> Vec<A::Item> { 1583 let cap = n + self.len(); 1584 let mut v = Vec::with_capacity(cap); 1585 let iter = self.iter_mut().map(take); 1586 v.extend(iter); 1587 self.set_len(0); 1588 return v; 1589 } 1590 1591 /// Drains all elements to a Vec 1592 /// ``` 1593 /// # use tinyvec::*; 1594 /// let mut av = array_vec!([i32; 7] => 1, 2, 3); 1595 /// let v = av.drain_to_vec(); 1596 /// assert_eq!(v, &[1, 2, 3]); 1597 /// assert_eq!(v.capacity(), 3); 1598 /// ``` drain_to_vec(&mut self) -> Vec<A::Item>1599 pub fn drain_to_vec(&mut self) -> Vec<A::Item> { 1600 self.drain_to_vec_and_reserve(0) 1601 } 1602 } 1603 1604 #[cfg(feature = "serde")] 1605 struct ArrayVecVisitor<A: Array>(PhantomData<A>); 1606 1607 #[cfg(feature = "serde")] 1608 impl<'de, A: Array> Visitor<'de> for ArrayVecVisitor<A> 1609 where 1610 A::Item: Deserialize<'de>, 1611 { 1612 type Value = ArrayVec<A>; 1613 expecting( &self, formatter: &mut core::fmt::Formatter, ) -> core::fmt::Result1614 fn expecting( 1615 &self, formatter: &mut core::fmt::Formatter, 1616 ) -> core::fmt::Result { 1617 formatter.write_str("a sequence") 1618 } 1619 visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error> where S: SeqAccess<'de>,1620 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error> 1621 where 1622 S: SeqAccess<'de>, 1623 { 1624 let mut new_arrayvec: ArrayVec<A> = Default::default(); 1625 1626 let mut idx = 0usize; 1627 while let Some(value) = seq.next_element()? { 1628 if new_arrayvec.len() >= new_arrayvec.capacity() { 1629 return Err(DeserializeError::invalid_length(idx, &self)); 1630 } 1631 new_arrayvec.push(value); 1632 idx = idx + 1; 1633 } 1634 1635 Ok(new_arrayvec) 1636 } 1637 } 1638