1 use super::*; 2 3 /// Helper to make an `ArrayVec`. 4 /// 5 /// You specify the backing array type, and optionally give all the elements you 6 /// want to initially place into the array. 7 /// 8 /// As an unfortunate restriction, the backing array type must support `Default` 9 /// for it to work with this macro. 10 /// 11 /// ```rust 12 /// use tinyvec::*; 13 /// 14 /// // The backing array type can be specified in the macro call 15 /// let empty_av = array_vec!([u8; 16]); 16 /// let some_ints = array_vec!([i32; 4], 1, 2, 3); 17 /// 18 /// // Or left to inference 19 /// let empty_av: ArrayVec<[u8; 10]> = array_vec!(); 20 /// let some_ints: ArrayVec<[u8; 10]> = array_vec!(5, 6, 7, 8); 21 /// ``` 22 #[macro_export] 23 macro_rules! array_vec { 24 ($array_type:ty) => { 25 { 26 let av: $crate::ArrayVec<$array_type> = Default::default(); 27 av 28 } 29 }; 30 ($array_type:ty, $($elem:expr),*) => { 31 { 32 let mut av: $crate::ArrayVec<$array_type> = Default::default(); 33 $( av.push($elem); )* 34 av 35 } 36 }; 37 () => { 38 array_vec!(_) 39 }; 40 ($($elem:expr),*) => { 41 array_vec!(_, $($elem),*) 42 }; 43 } 44 45 /// An array-backed, vector-like data structure. 46 /// 47 /// * `ArrayVec` has a fixed capacity, equal to the array size. 48 /// * `ArrayVec` has a variable length, as you add and remove elements. Attempts 49 /// to fill the vec beyond its capacity will cause a panic. 50 /// * All of the vec's array slots are always initialized in terms of Rust's 51 /// memory model. When you remove a element from a location, the old value at 52 /// that location is replaced with the type's default value. 53 /// 54 /// The overall API of this type is intended to, as much as possible, emulate 55 /// the API of the [`Vec`](https://doc.rust-lang.org/alloc/vec/struct.Vec.html) 56 /// type. 57 /// 58 /// ## Construction 59 /// 60 /// If the backing array supports Default (length 32 or less), then you can use 61 /// the `array_vec!` macro similarly to how you might use the `vec!` macro. 62 /// Specify the array type, then optionally give all the initial values you want 63 /// to have. 64 /// ```rust 65 /// # use tinyvec::*; 66 /// let some_ints = array_vec!([i32; 4], 1, 2, 3); 67 /// assert_eq!(some_ints.len(), 3); 68 /// ``` 69 /// 70 /// The [`default`](ArrayVec::new) for an `ArrayVec` is to have a default 71 /// array with length 0. The [`new`](ArrayVec::new) method is the same as 72 /// calling `default` 73 /// ```rust 74 /// # use tinyvec::*; 75 /// let some_ints = ArrayVec::<[i32; 7]>::default(); 76 /// assert_eq!(some_ints.len(), 0); 77 /// 78 /// let more_ints = ArrayVec::<[i32; 7]>::new(); 79 /// assert_eq!(some_ints, more_ints); 80 /// ``` 81 /// 82 /// If you have an array and want the _whole thing_ so count as being "in" the 83 /// new `ArrayVec` you can use one of the `from` implementations. If you want 84 /// _part of_ the array then you can use 85 /// [`from_array_len`](ArrayVec::from_array_len): 86 /// ```rust 87 /// # use tinyvec::*; 88 /// let some_ints = ArrayVec::from([5, 6, 7, 8]); 89 /// assert_eq!(some_ints.len(), 4); 90 /// 91 /// let more_ints = ArrayVec::from_array_len([5, 6, 7, 8], 2); 92 /// assert_eq!(more_ints.len(), 2); 93 /// ``` 94 #[repr(C)] 95 #[derive(Clone, Copy, Default)] 96 pub struct ArrayVec<A: Array> { 97 len: usize, 98 data: A, 99 } 100 101 impl<A: Array> Deref for ArrayVec<A> { 102 type Target = [A::Item]; 103 #[inline(always)] 104 #[must_use] deref(&self) -> &Self::Target105 fn deref(&self) -> &Self::Target { 106 &self.data.as_slice()[..self.len] 107 } 108 } 109 110 impl<A: Array> DerefMut for ArrayVec<A> { 111 #[inline(always)] 112 #[must_use] deref_mut(&mut self) -> &mut Self::Target113 fn deref_mut(&mut self) -> &mut Self::Target { 114 &mut self.data.as_slice_mut()[..self.len] 115 } 116 } 117 118 impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for ArrayVec<A> { 119 type Output = <I as SliceIndex<[A::Item]>>::Output; 120 #[inline(always)] 121 #[must_use] index(&self, index: I) -> &Self::Output122 fn index(&self, index: I) -> &Self::Output { 123 &self.deref()[index] 124 } 125 } 126 127 impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for ArrayVec<A> { 128 #[inline(always)] 129 #[must_use] index_mut(&mut self, index: I) -> &mut Self::Output130 fn index_mut(&mut self, index: I) -> &mut Self::Output { 131 &mut self.deref_mut()[index] 132 } 133 } 134 135 impl<A: Array> ArrayVec<A> { 136 /// Move all values from `other` into this vec. 137 /// 138 /// ## Panics 139 /// * If the vec overflows its capacity 140 /// 141 /// ## Example 142 /// ```rust 143 /// # use tinyvec::*; 144 /// let mut av = array_vec!([i32; 10], 1, 2, 3); 145 /// let mut av2 = array_vec!([i32; 10], 4, 5, 6); 146 /// av.append(&mut av2); 147 /// assert_eq!(av, &[1, 2, 3, 4, 5, 6][..]); 148 /// assert_eq!(av2, &[][..]); 149 /// ``` 150 #[inline] append(&mut self, other: &mut Self)151 pub fn append(&mut self, other: &mut Self) { 152 for item in other.drain(..) { 153 self.push(item) 154 } 155 } 156 157 /// A `*mut` pointer to the backing array. 158 /// 159 /// ## Safety 160 /// 161 /// This pointer has provenance over the _entire_ backing array. 162 #[inline(always)] 163 #[must_use] as_mut_ptr(&mut self) -> *mut A::Item164 pub fn as_mut_ptr(&mut self) -> *mut A::Item { 165 self.data.as_slice_mut().as_mut_ptr() 166 } 167 168 /// Performs a `deref_mut`, into unique slice form. 169 #[inline(always)] 170 #[must_use] as_mut_slice(&mut self) -> &mut [A::Item]171 pub fn as_mut_slice(&mut self) -> &mut [A::Item] { 172 self.deref_mut() 173 } 174 175 /// A `*const` pointer to the backing array. 176 /// 177 /// ## Safety 178 /// 179 /// This pointer has provenance over the _entire_ backing array. 180 #[inline(always)] 181 #[must_use] as_ptr(&self) -> *const A::Item182 pub fn as_ptr(&self) -> *const A::Item { 183 self.data.as_slice().as_ptr() 184 } 185 186 /// Performs a `deref`, into shared slice form. 187 #[inline(always)] 188 #[must_use] as_slice(&self) -> &[A::Item]189 pub fn as_slice(&self) -> &[A::Item] { 190 self.deref() 191 } 192 193 /// The capacity of the `ArrayVec`. 194 /// 195 /// This is fixed based on the array type, but can't yet be made a `const fn` 196 /// on Stable Rust. 197 #[inline(always)] 198 #[must_use] capacity(&self) -> usize199 pub fn capacity(&self) -> usize { 200 A::CAPACITY 201 } 202 203 /// Truncates the `ArrayVec` down to length 0. 204 #[inline(always)] clear(&mut self)205 pub fn clear(&mut self) { 206 self.truncate(0) 207 } 208 209 /// Creates a draining iterator that removes the specified range in the vector 210 /// and yields the removed items. 211 /// 212 /// ## Panics 213 /// * If the start is greater than the end 214 /// * If the end is past the edge of the vec. 215 /// 216 /// ## Example 217 /// ```rust 218 /// # use tinyvec::*; 219 /// let mut av = array_vec!([i32; 4], 1, 2, 3); 220 /// let av2: ArrayVec<[i32; 4]> = av.drain(1..).collect(); 221 /// assert_eq!(av.as_slice(), &[1][..]); 222 /// assert_eq!(av2.as_slice(), &[2, 3][..]); 223 /// 224 /// av.drain(..); 225 /// assert_eq!(av.as_slice(), &[]); 226 /// ``` 227 #[inline] drain<R: RangeBounds<usize>>( &mut self, range: R, ) -> ArrayVecDrain<'_, A>228 pub fn drain<R: RangeBounds<usize>>( 229 &mut self, 230 range: R, 231 ) -> ArrayVecDrain<'_, A> { 232 use core::ops::Bound; 233 let start = match range.start_bound() { 234 Bound::Included(x) => *x, 235 Bound::Excluded(x) => x + 1, 236 Bound::Unbounded => 0, 237 }; 238 let end = match range.end_bound() { 239 Bound::Included(x) => x + 1, 240 Bound::Excluded(x) => *x, 241 Bound::Unbounded => self.len, 242 }; 243 assert!( 244 start <= end, 245 "ArrayVec::drain> Illegal range, {} to {}", 246 start, 247 end 248 ); 249 assert!( 250 end <= self.len, 251 "ArrayVec::drain> Range ends at {} but length is only {}!", 252 end, 253 self.len 254 ); 255 ArrayVecDrain { 256 parent: self, 257 target_start: start, 258 target_index: start, 259 target_end: end, 260 } 261 } 262 263 /// Clone each element of the slice into this `ArrayVec`. 264 /// 265 /// ## Panics 266 /// * If the `ArrayVec` would overflow, this will panic. 267 #[inline] extend_from_slice(&mut self, sli: &[A::Item]) where A::Item: Clone,268 pub fn extend_from_slice(&mut self, sli: &[A::Item]) 269 where 270 A::Item: Clone, 271 { 272 if sli.is_empty() { 273 return; 274 } 275 276 let new_len = self.len + sli.len(); 277 if new_len > A::CAPACITY { 278 panic!( 279 "ArrayVec::extend_from_slice> total length {} exceeds capacity {}!", 280 new_len, 281 A::CAPACITY 282 ) 283 } 284 285 let target = &mut self.data.as_slice_mut()[self.len..new_len]; 286 target.clone_from_slice(sli); 287 self.set_len(new_len); 288 } 289 290 /// Wraps up an array and uses the given length as the initial length. 291 /// 292 /// If you want to simply use the full array, use `from` instead. 293 /// 294 /// ## Panics 295 /// 296 /// * The length specified must be less than or equal to the capacity of the array. 297 #[inline] 298 #[must_use] 299 #[allow(clippy::match_wild_err_arm)] from_array_len(data: A, len: usize) -> Self300 pub fn from_array_len(data: A, len: usize) -> Self { 301 match Self::try_from_array_len(data, len) { 302 Ok(out) => out, 303 Err(_) => { 304 panic!("ArrayVec::from_array_len> length {} exceeds capacity {}!", len, A::CAPACITY) 305 } 306 } 307 } 308 309 /// Inserts an item at the position given, moving all following elements +1 310 /// index. 311 /// 312 /// ## Panics 313 /// * If `index` > `len` or 314 /// * If the capacity is exhausted 315 /// 316 /// ## Example 317 /// ```rust 318 /// use tinyvec::*; 319 /// let mut av = array_vec!([i32; 10], 1, 2, 3); 320 /// av.insert(1, 4); 321 /// assert_eq!(av.as_slice(), &[1, 4, 2, 3]); 322 /// av.insert(4, 5); 323 /// assert_eq!(av.as_slice(), &[1, 4, 2, 3, 5]); 324 /// ``` 325 #[inline] insert(&mut self, index: usize, item: A::Item)326 pub fn insert(&mut self, index: usize, item: A::Item) { 327 if index > self.len { 328 panic!("ArrayVec::insert> index {} is out of bounds {}", index, self.len); 329 } 330 331 // Try to push the element. 332 self.push(item); 333 // And move it into its place. 334 self.as_mut_slice()[index..].rotate_right(1); 335 } 336 337 /// Checks if the length is 0. 338 #[inline(always)] 339 #[must_use] is_empty(&self) -> bool340 pub fn is_empty(&self) -> bool { 341 self.len == 0 342 } 343 344 /// The length of the `ArrayVec` (in elements). 345 #[inline(always)] 346 #[must_use] len(&self) -> usize347 pub fn len(&self) -> usize { 348 self.len 349 } 350 351 /// Makes a new, empty `ArrayVec`. 352 #[inline(always)] 353 #[must_use] new() -> Self where A: Default,354 pub fn new() -> Self 355 where 356 A: Default, 357 { 358 Self::default() 359 } 360 361 /// Remove and return the last element of the vec, if there is one. 362 /// 363 /// ## Failure 364 /// * If the vec is empty you get `None`. 365 /// 366 /// ## Example 367 /// ```rust 368 /// # use tinyvec::*; 369 /// let mut av = array_vec!([i32; 10], 1, 2); 370 /// assert_eq!(av.pop(), Some(2)); 371 /// assert_eq!(av.pop(), Some(1)); 372 /// assert_eq!(av.pop(), None); 373 /// ``` 374 #[inline] pop(&mut self) -> Option<A::Item>375 pub fn pop(&mut self) -> Option<A::Item> { 376 if self.len > 0 { 377 self.len -= 1; 378 let out = take(&mut self.data.as_slice_mut()[self.len]); 379 Some(out) 380 } else { 381 None 382 } 383 } 384 385 /// Place an element onto the end of the vec. 386 /// 387 /// ## Panics 388 /// * If the length of the vec would overflow the capacity. 389 /// 390 /// ## Example 391 /// ```rust 392 /// # use tinyvec::*; 393 /// let mut av = array_vec!([i32; 2]); 394 /// assert_eq!(&av[..], []); 395 /// av.push(1); 396 /// assert_eq!(&av[..], [1]); 397 /// av.push(2); 398 /// assert_eq!(&av[..], [1, 2]); 399 /// // av.push(3); this would overflow the ArrayVec and panic! 400 /// ``` 401 #[inline(always)] push(&mut self, val: A::Item)402 pub fn push(&mut self, val: A::Item) { 403 if self.len < A::CAPACITY { 404 replace(&mut self.data.as_slice_mut()[self.len], val); 405 self.len += 1; 406 } else { 407 panic!("ArrayVec::push> capacity overflow!") 408 } 409 } 410 411 /// Removes the item at `index`, shifting all others down by one index. 412 /// 413 /// Returns the removed element. 414 /// 415 /// ## Panics 416 /// 417 /// * If the index is out of bounds. 418 /// 419 /// ## Example 420 /// 421 /// ```rust 422 /// # use tinyvec::*; 423 /// let mut av = array_vec!([i32; 4], 1, 2, 3); 424 /// assert_eq!(av.remove(1), 2); 425 /// assert_eq!(&av[..], [1, 3]); 426 /// ``` 427 #[inline] remove(&mut self, index: usize) -> A::Item428 pub fn remove(&mut self, index: usize) -> A::Item { 429 let targets: &mut [A::Item] = &mut self.deref_mut()[index..]; 430 let item = replace(&mut targets[0], A::Item::default()); 431 targets.rotate_left(1); 432 self.len -= 1; 433 item 434 } 435 436 /// Resize the vec to the new length. 437 /// 438 /// If it needs to be longer, it's filled with clones of the provided value. 439 /// If it needs to be shorter, it's truncated. 440 /// 441 /// ## Example 442 /// 443 /// ```rust 444 /// # use tinyvec::*; 445 /// 446 /// let mut av = array_vec!([&str; 10], "hello"); 447 /// av.resize(3, "world"); 448 /// assert_eq!(&av[..], ["hello", "world", "world"]); 449 /// 450 /// let mut av = array_vec!([i32; 10], 1, 2, 3, 4); 451 /// av.resize(2, 0); 452 /// assert_eq!(&av[..], [1, 2]); 453 /// ``` 454 #[inline] resize(&mut self, new_len: usize, new_val: A::Item) where A::Item: Clone,455 pub fn resize(&mut self, new_len: usize, new_val: A::Item) 456 where 457 A::Item: Clone, 458 { 459 match new_len.checked_sub(self.len) { 460 None => self.truncate(new_len), 461 Some(0) => (), 462 Some(new_elements) => { 463 for _ in 1..new_elements { 464 self.push(new_val.clone()); 465 } 466 self.push(new_val); 467 } 468 } 469 } 470 471 /// Resize the vec to the new length. 472 /// 473 /// If it needs to be longer, it's filled with repeated calls to the provided 474 /// function. If it needs to be shorter, it's truncated. 475 /// 476 /// ## Example 477 /// 478 /// ```rust 479 /// # use tinyvec::*; 480 /// 481 /// let mut av = array_vec!([i32; 10], 1, 2, 3); 482 /// av.resize_with(5, Default::default); 483 /// assert_eq!(&av[..], [1, 2, 3, 0, 0]); 484 /// 485 /// let mut av = array_vec!([i32; 10]); 486 /// let mut p = 1; 487 /// av.resize_with(4, || { p *= 2; p }); 488 /// assert_eq!(&av[..], [2, 4, 8, 16]); 489 /// ``` 490 #[inline] resize_with<F: FnMut() -> A::Item>( &mut self, new_len: usize, mut f: F, )491 pub fn resize_with<F: FnMut() -> A::Item>( 492 &mut self, 493 new_len: usize, 494 mut f: F, 495 ) { 496 match new_len.checked_sub(self.len) { 497 None => self.truncate(new_len), 498 Some(new_elements) => { 499 for _ in 0..new_elements { 500 self.push(f()); 501 } 502 } 503 } 504 } 505 506 /// Walk the vec and keep only the elements that pass the predicate given. 507 /// 508 /// ## Example 509 /// 510 /// ```rust 511 /// # use tinyvec::*; 512 /// 513 /// let mut av = array_vec!([i32; 10], 1, 1, 2, 3, 3, 4); 514 /// av.retain(|&x| x % 2 == 0); 515 /// assert_eq!(&av[..], [2, 4]); 516 /// ``` 517 #[inline] retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F)518 pub fn retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F) { 519 // Drop guard to contain exactly the remaining elements when the test 520 // panics. 521 struct JoinOnDrop<'vec, Item> { 522 items: &'vec mut [Item], 523 done_end: usize, 524 // Start of tail relative to `done_end`. 525 tail_start: usize, 526 } 527 528 impl<Item> Drop for JoinOnDrop<'_, Item> { 529 fn drop(&mut self) { 530 self.items[self.done_end..].rotate_left(self.tail_start); 531 } 532 } 533 534 let mut rest = JoinOnDrop { 535 items: &mut self.data.as_slice_mut()[..self.len], 536 done_end: 0, 537 tail_start: 0, 538 }; 539 540 for idx in 0..self.len { 541 // Loop start invariant: idx = rest.done_end + rest.tail_start 542 if !acceptable(&rest.items[idx]) { 543 let _ = take(&mut rest.items[idx]); 544 self.len -= 1; 545 rest.tail_start += 1; 546 } else { 547 rest.items.swap(rest.done_end, idx); 548 rest.done_end += 1; 549 } 550 } 551 } 552 553 /// Forces the length of the vector to `new_len`. 554 /// 555 /// ## Panics 556 /// * If `new_len` is greater than the vec's capacity. 557 /// 558 /// ## Safety 559 /// * This is a fully safe operation! The inactive memory already counts as 560 /// "initialized" by Rust's rules. 561 /// * Other than "the memory is initialized" there are no other guarantees 562 /// regarding what you find in the inactive portion of the vec. 563 #[inline(always)] set_len(&mut self, new_len: usize)564 pub fn set_len(&mut self, new_len: usize) { 565 if new_len > A::CAPACITY { 566 // Note(Lokathor): Technically we don't have to panic here, and we could 567 // just let some other call later on trigger a panic on accident when the 568 // length is wrong. However, it's a lot easier to catch bugs when things 569 // are more "fail-fast". 570 panic!("ArrayVec: set_len overflow!") 571 } else { 572 self.len = new_len; 573 } 574 } 575 576 /// Fill the vector until its capacity has been reached. 577 /// 578 /// Successively fills unused space in the spare slice of the vector with 579 /// elements from the iterator. It then returns the remaining iterator 580 /// without exhausting it. This also allows appending the head of an 581 /// infinite iterator. 582 /// 583 /// This is an alternative to `Extend::extend` method for cases where the 584 /// length of the iterator can not be checked. Since this vector can not 585 /// reallocate to increase its capacity, it is unclear what to do with 586 /// remaining elements in the iterator and the iterator itself. The 587 /// interface also provides no way to communicate this to the caller. 588 /// 589 /// ## Panics 590 /// * If the `next` method of the provided iterator panics. 591 /// 592 /// ## Example 593 /// 594 /// ```rust 595 /// # use tinyvec::*; 596 /// let mut av = array_vec!([i32; 4]); 597 /// let mut to_inf = av.fill(0..); 598 /// assert_eq!(&av[..], [0, 1, 2, 3]); 599 /// assert_eq!(to_inf.next(), Some(4)); 600 /// ``` 601 #[inline] fill<I: IntoIterator<Item = A::Item>>( &mut self, iter: I, ) -> I::IntoIter602 pub fn fill<I: IntoIterator<Item = A::Item>>( 603 &mut self, 604 iter: I, 605 ) -> I::IntoIter { 606 let mut iter = iter.into_iter(); 607 for element in iter.by_ref().take(self.capacity() - self.len()) { 608 self.push(element); 609 } 610 iter 611 } 612 613 /// Splits the collection at the point given. 614 /// 615 /// * `[0, at)` stays in this vec 616 /// * `[at, len)` ends up in the new vec. 617 /// 618 /// ## Panics 619 /// * if at > len 620 /// 621 /// ## Example 622 /// 623 /// ```rust 624 /// # use tinyvec::*; 625 /// let mut av = array_vec!([i32; 4], 1, 2, 3); 626 /// let av2 = av.split_off(1); 627 /// assert_eq!(&av[..], [1]); 628 /// assert_eq!(&av2[..], [2, 3]); 629 /// ``` 630 #[inline] split_off(&mut self, at: usize) -> Self where Self: Default,631 pub fn split_off(&mut self, at: usize) -> Self 632 where 633 Self: Default, 634 { 635 // FIXME: should this just use drain into the output? 636 if at > self.len { 637 panic!( 638 "ArrayVec::split_off> at value {} exceeds length of {}", 639 at, self.len 640 ); 641 } 642 let mut new = Self::default(); 643 let moves = &mut self.as_mut_slice()[at..]; 644 let split_len = moves.len(); 645 let targets = &mut new.data.as_slice_mut()[..split_len]; 646 moves.swap_with_slice(targets); 647 new.len = split_len; 648 self.len = at; 649 new 650 } 651 652 /// Remove an element, swapping the end of the vec into its place. 653 /// 654 /// ## Panics 655 /// * If the index is out of bounds. 656 /// 657 /// ## Example 658 /// ```rust 659 /// # use tinyvec::*; 660 /// let mut av = array_vec!([&str; 4], "foo", "bar", "quack", "zap"); 661 /// 662 /// assert_eq!(av.swap_remove(1), "bar"); 663 /// assert_eq!(&av[..], ["foo", "zap", "quack"]); 664 /// 665 /// assert_eq!(av.swap_remove(0), "foo"); 666 /// assert_eq!(&av[..], ["quack", "zap"]); 667 /// ``` 668 #[inline] swap_remove(&mut self, index: usize) -> A::Item669 pub fn swap_remove(&mut self, index: usize) -> A::Item { 670 assert!( 671 index < self.len, 672 "ArrayVec::swap_remove> index {} is out of bounds {}", 673 index, 674 self.len 675 ); 676 if index == self.len - 1 { 677 self.pop().unwrap() 678 } else { 679 let i = self.pop().unwrap(); 680 replace(&mut self[index], i) 681 } 682 } 683 684 /// Reduces the vec's length to the given value. 685 /// 686 /// If the vec is already shorter than the input, nothing happens. 687 #[inline] truncate(&mut self, new_len: usize)688 pub fn truncate(&mut self, new_len: usize) { 689 if needs_drop::<A::Item>() { 690 while self.len > new_len { 691 self.pop(); 692 } 693 } else { 694 self.len = self.len.min(new_len); 695 } 696 } 697 698 /// Wraps an array, using the given length as the starting length. 699 /// 700 /// If you want to use the whole length of the array, you can just use the 701 /// `From` impl. 702 /// 703 /// ## Failure 704 /// 705 /// If the given length is greater than the capacity of the array this will 706 /// error, and you'll get the array back in the `Err`. 707 #[inline] try_from_array_len(data: A, len: usize) -> Result<Self, A>708 pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> { 709 if len <= A::CAPACITY { 710 Ok(Self { data, len }) 711 } else { 712 Err(data) 713 } 714 } 715 } 716 717 #[cfg(feature = "grab_spare_slice")] 718 impl<A: Array> ArrayVec<A> { 719 /// Obtain the shared slice of the array _after_ the active memory. 720 /// 721 /// ## Example 722 /// ```rust 723 /// # use tinyvec::*; 724 /// let mut av = array_vec!([i32; 4]); 725 /// assert_eq!(av.grab_spare_slice().len(), 4); 726 /// av.push(10); 727 /// av.push(11); 728 /// av.push(12); 729 /// av.push(13); 730 /// assert_eq!(av.grab_spare_slice().len(), 0); 731 /// ``` 732 #[inline(always)] grab_spare_slice(&self) -> &[A::Item]733 pub fn grab_spare_slice(&self) -> &[A::Item] { 734 &self.data.as_slice()[self.len..] 735 } 736 737 /// Obtain the mutable slice of the array _after_ the active memory. 738 /// 739 /// ## Example 740 /// ```rust 741 /// # use tinyvec::*; 742 /// let mut av = array_vec!([i32; 4]); 743 /// assert_eq!(av.grab_spare_slice_mut().len(), 4); 744 /// av.push(10); 745 /// av.push(11); 746 /// assert_eq!(av.grab_spare_slice_mut().len(), 2); 747 /// ``` 748 #[inline(always)] grab_spare_slice_mut(&mut self) -> &mut [A::Item]749 pub fn grab_spare_slice_mut(&mut self) -> &mut [A::Item] { 750 &mut self.data.as_slice_mut()[self.len..] 751 } 752 } 753 754 #[cfg(feature = "nightly_slice_partition_dedup")] 755 impl<A: Array> ArrayVec<A> { 756 /// De-duplicates the vec contents. 757 #[inline(always)] dedup(&mut self) where A::Item: PartialEq,758 pub fn dedup(&mut self) 759 where 760 A::Item: PartialEq, 761 { 762 self.dedup_by(|a, b| a == b) 763 } 764 765 /// De-duplicates the vec according to the predicate given. 766 #[inline(always)] dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut A::Item, &mut A::Item) -> bool,767 pub fn dedup_by<F>(&mut self, same_bucket: F) 768 where 769 F: FnMut(&mut A::Item, &mut A::Item) -> bool, 770 { 771 let len = { 772 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket); 773 dedup.len() 774 }; 775 self.truncate(len); 776 } 777 778 /// De-duplicates the vec according to the key selector given. 779 #[inline(always)] dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut A::Item) -> K, K: PartialEq,780 pub fn dedup_by_key<F, K>(&mut self, mut key: F) 781 where 782 F: FnMut(&mut A::Item) -> K, 783 K: PartialEq, 784 { 785 self.dedup_by(|a, b| key(a) == key(b)) 786 } 787 } 788 789 /// Draining iterator for `ArrayVecDrain` 790 /// 791 /// See [`ArrayVec::drain`](ArrayVec::drain) 792 pub struct ArrayVecDrain<'p, A: Array> { 793 parent: &'p mut ArrayVec<A>, 794 target_start: usize, 795 target_index: usize, 796 target_end: usize, 797 } 798 impl<'p, A: Array> Iterator for ArrayVecDrain<'p, A> { 799 type Item = A::Item; 800 #[inline] next(&mut self) -> Option<Self::Item>801 fn next(&mut self) -> Option<Self::Item> { 802 if self.target_index != self.target_end { 803 let out = take(&mut self.parent[self.target_index]); 804 self.target_index += 1; 805 Some(out) 806 } else { 807 None 808 } 809 } 810 } 811 impl<'p, A: Array> FusedIterator for ArrayVecDrain<'p, A> { } 812 impl<'p, A: Array> Drop for ArrayVecDrain<'p, A> { 813 #[inline] drop(&mut self)814 fn drop(&mut self) { 815 // Changed because it was moving `self`, it's also more clear and the std does the same 816 self.for_each(drop); 817 // Implementation very similar to [`ArrayVec::remove`](ArrayVec::remove) 818 let count = self.target_end - self.target_start; 819 let targets: &mut [A::Item] = &mut self.parent.deref_mut()[self.target_start..]; 820 targets.rotate_left(count); 821 self.parent.len -= count; 822 } 823 } 824 825 impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> { 826 #[inline(always)] 827 #[must_use] as_mut(&mut self) -> &mut [A::Item]828 fn as_mut(&mut self) -> &mut [A::Item] { 829 &mut *self 830 } 831 } 832 833 impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> { 834 #[inline(always)] 835 #[must_use] as_ref(&self) -> &[A::Item]836 fn as_ref(&self) -> &[A::Item] { 837 &*self 838 } 839 } 840 841 impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> { 842 #[inline(always)] 843 #[must_use] borrow(&self) -> &[A::Item]844 fn borrow(&self) -> &[A::Item] { 845 &*self 846 } 847 } 848 849 impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> { 850 #[inline(always)] 851 #[must_use] borrow_mut(&mut self) -> &mut [A::Item]852 fn borrow_mut(&mut self) -> &mut [A::Item] { 853 &mut *self 854 } 855 } 856 857 impl<A: Array> Extend<A::Item> for ArrayVec<A> { 858 #[inline] extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T)859 fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) { 860 for t in iter { 861 self.push(t) 862 } 863 } 864 } 865 866 impl<A: Array> From<A> for ArrayVec<A> { 867 #[inline(always)] 868 #[must_use] 869 /// The output has a length equal to the full array. 870 /// 871 /// If you want to select a length, use 872 /// [`from_array_len`](ArrayVec::from_array_len) from(data: A) -> Self873 fn from(data: A) -> Self { 874 Self { len: data.as_slice().len(), data } 875 } 876 } 877 878 impl<A: Array + Default> FromIterator<A::Item> for ArrayVec<A> { 879 #[inline] 880 #[must_use] from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self881 fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self { 882 let mut av = Self::default(); 883 for i in iter { 884 av.push(i) 885 } 886 av 887 } 888 } 889 890 /// Iterator for consuming an `ArrayVec` and returning owned elements. 891 pub struct ArrayVecIterator<A: Array> { 892 base: usize, 893 len: usize, 894 data: A, 895 } 896 897 impl<A: Array> ArrayVecIterator<A> { 898 /// Returns the remaining items of this iterator as a slice. 899 #[inline] 900 #[must_use] as_slice(&self) -> &[A::Item]901 pub fn as_slice(&self) -> &[A::Item] { 902 &self.data.as_slice()[self.base..self.len] 903 } 904 } 905 impl<A: Array> FusedIterator for ArrayVecIterator<A> { } 906 impl<A: Array> Iterator for ArrayVecIterator<A> { 907 type Item = A::Item; 908 #[inline] next(&mut self) -> Option<Self::Item>909 fn next(&mut self) -> Option<Self::Item> { 910 if self.base < self.len { 911 let out = take(&mut self.data.as_slice_mut()[self.base]); 912 self.base += 1; 913 Some(out) 914 } else { 915 None 916 } 917 } 918 #[inline(always)] 919 #[must_use] size_hint(&self) -> (usize, Option<usize>)920 fn size_hint(&self) -> (usize, Option<usize>) { 921 let s = self.len - self.base; 922 (s, Some(s)) 923 } 924 #[inline(always)] count(self) -> usize925 fn count(self) -> usize { 926 self.len - self.base 927 } 928 #[inline] last(mut self) -> Option<Self::Item>929 fn last(mut self) -> Option<Self::Item> { 930 Some(take(&mut self.data.as_slice_mut()[self.len])) 931 } 932 #[inline] nth(&mut self, n: usize) -> Option<A::Item>933 fn nth(&mut self, n: usize) -> Option<A::Item> { 934 let i = self.base + (n - 1); 935 if i < self.len { 936 let out = take(&mut self.data.as_slice_mut()[i]); 937 self.base = i + 1; 938 Some(out) 939 } else { 940 None 941 } 942 } 943 } 944 945 impl<A: Array> Debug for ArrayVecIterator<A> where A::Item: Debug { 946 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result947 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { 948 f.debug_tuple("ArrayVecIterator").field(&self.as_slice()).finish() 949 } 950 } 951 952 impl<A: Array> IntoIterator for ArrayVec<A> { 953 type Item = A::Item; 954 type IntoIter = ArrayVecIterator<A>; 955 #[inline(always)] 956 #[must_use] into_iter(self) -> Self::IntoIter957 fn into_iter(self) -> Self::IntoIter { 958 ArrayVecIterator { base: 0, len: self.len, data: self.data } 959 } 960 } 961 962 impl<A: Array> PartialEq for ArrayVec<A> 963 where 964 A::Item: PartialEq, 965 { 966 #[inline] 967 #[must_use] eq(&self, other: &Self) -> bool968 fn eq(&self, other: &Self) -> bool { 969 self.as_slice().eq(other.as_slice()) 970 } 971 } 972 impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq {} 973 974 impl<A: Array> PartialOrd for ArrayVec<A> 975 where 976 A::Item: PartialOrd, 977 { 978 #[inline] 979 #[must_use] partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering>980 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { 981 self.as_slice().partial_cmp(other.as_slice()) 982 } 983 } 984 impl<A: Array> Ord for ArrayVec<A> 985 where 986 A::Item: Ord, 987 { 988 #[inline] 989 #[must_use] cmp(&self, other: &Self) -> core::cmp::Ordering990 fn cmp(&self, other: &Self) -> core::cmp::Ordering { 991 self.as_slice().cmp(other.as_slice()) 992 } 993 } 994 995 impl<A: Array> PartialEq<&A> for ArrayVec<A> 996 where 997 A::Item: PartialEq, 998 { 999 #[inline] 1000 #[must_use] eq(&self, other: &&A) -> bool1001 fn eq(&self, other: &&A) -> bool { 1002 self.as_slice().eq(other.as_slice()) 1003 } 1004 } 1005 1006 impl<A: Array> PartialEq<&[A::Item]> for ArrayVec<A> 1007 where 1008 A::Item: PartialEq, 1009 { 1010 #[inline] 1011 #[must_use] eq(&self, other: &&[A::Item]) -> bool1012 fn eq(&self, other: &&[A::Item]) -> bool { 1013 self.as_slice().eq(*other) 1014 } 1015 } 1016 1017 impl<A: Array> Hash for ArrayVec<A> 1018 where 1019 A::Item: Hash, 1020 { 1021 #[inline] hash<H: Hasher>(&self, state: &mut H)1022 fn hash<H: Hasher>(&self, state: &mut H) { 1023 self.as_slice().hash(state) 1024 } 1025 } 1026 1027 #[cfg(feature = "experimental_write_impl")] 1028 impl<A: Array<Item=u8>> core::fmt::Write for ArrayVec<A> 1029 { write_str(&mut self, s: &str) -> core::fmt::Result1030 fn write_str(&mut self, s: &str) -> core::fmt::Result { 1031 let my_len = self.len(); 1032 let str_len = s.as_bytes().len(); 1033 if my_len + str_len <= A::CAPACITY { 1034 let remainder = &mut self.data.as_slice_mut()[my_len..]; 1035 let target = &mut remainder[..str_len]; 1036 target.copy_from_slice(s.as_bytes()); 1037 Ok(()) 1038 } else { 1039 Err(core::fmt::Error) 1040 } 1041 } 1042 } 1043 1044 // // // // // // // // 1045 // Formatting impls 1046 // // // // // // // // 1047 1048 impl<A: Array> Binary for ArrayVec<A> 1049 where 1050 A::Item: Binary, 1051 { 1052 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1053 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1054 write!(f, "[")?; 1055 for (i, elem) in self.iter().enumerate() { 1056 if i > 0 { 1057 write!(f, ", ")?; 1058 } 1059 Binary::fmt(elem, f)?; 1060 } 1061 write!(f, "]") 1062 } 1063 } 1064 1065 impl<A: Array> Debug for ArrayVec<A> 1066 where 1067 A::Item: Debug, 1068 { 1069 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1070 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1071 write!(f, "[")?; 1072 for (i, elem) in self.iter().enumerate() { 1073 if i > 0 { 1074 write!(f, ", ")?; 1075 } 1076 Debug::fmt(elem, f)?; 1077 } 1078 write!(f, "]") 1079 } 1080 } 1081 1082 impl<A: Array> Display for ArrayVec<A> 1083 where 1084 A::Item: Display, 1085 { 1086 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1087 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1088 write!(f, "[")?; 1089 for (i, elem) in self.iter().enumerate() { 1090 if i > 0 { 1091 write!(f, ", ")?; 1092 } 1093 Display::fmt(elem, f)?; 1094 } 1095 write!(f, "]") 1096 } 1097 } 1098 1099 impl<A: Array> LowerExp for ArrayVec<A> 1100 where 1101 A::Item: LowerExp, 1102 { 1103 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1104 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1105 write!(f, "[")?; 1106 for (i, elem) in self.iter().enumerate() { 1107 if i > 0 { 1108 write!(f, ", ")?; 1109 } 1110 LowerExp::fmt(elem, f)?; 1111 } 1112 write!(f, "]") 1113 } 1114 } 1115 1116 impl<A: Array> LowerHex for ArrayVec<A> 1117 where 1118 A::Item: LowerHex, 1119 { 1120 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1121 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1122 write!(f, "[")?; 1123 for (i, elem) in self.iter().enumerate() { 1124 if i > 0 { 1125 write!(f, ", ")?; 1126 } 1127 LowerHex::fmt(elem, f)?; 1128 } 1129 write!(f, "]") 1130 } 1131 } 1132 1133 impl<A: Array> Octal for ArrayVec<A> 1134 where 1135 A::Item: Octal, 1136 { 1137 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1138 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1139 write!(f, "[")?; 1140 for (i, elem) in self.iter().enumerate() { 1141 if i > 0 { 1142 write!(f, ", ")?; 1143 } 1144 Octal::fmt(elem, f)?; 1145 } 1146 write!(f, "]") 1147 } 1148 } 1149 1150 impl<A: Array> Pointer for ArrayVec<A> 1151 where 1152 A::Item: Pointer, 1153 { 1154 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1155 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1156 write!(f, "[")?; 1157 for (i, elem) in self.iter().enumerate() { 1158 if i > 0 { 1159 write!(f, ", ")?; 1160 } 1161 Pointer::fmt(elem, f)?; 1162 } 1163 write!(f, "]") 1164 } 1165 } 1166 1167 impl<A: Array> UpperExp for ArrayVec<A> 1168 where 1169 A::Item: UpperExp, 1170 { 1171 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1172 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1173 write!(f, "[")?; 1174 for (i, elem) in self.iter().enumerate() { 1175 if i > 0 { 1176 write!(f, ", ")?; 1177 } 1178 UpperExp::fmt(elem, f)?; 1179 } 1180 write!(f, "]") 1181 } 1182 } 1183 1184 impl<A: Array> UpperHex for ArrayVec<A> 1185 where 1186 A::Item: UpperHex, 1187 { 1188 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1189 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1190 write!(f, "[")?; 1191 for (i, elem) in self.iter().enumerate() { 1192 if i > 0 { 1193 write!(f, ", ")?; 1194 } 1195 UpperHex::fmt(elem, f)?; 1196 } 1197 write!(f, "]") 1198 } 1199 } 1200