1 #![cfg(feature = "alloc")] 2 3 use super::*; 4 5 use alloc::vec::{self, Vec}; 6 use core::convert::TryFrom; 7 use tinyvec_macros::impl_mirrored; 8 9 #[cfg(feature = "serde")] 10 use core::marker::PhantomData; 11 #[cfg(feature = "serde")] 12 use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor}; 13 #[cfg(feature = "serde")] 14 use serde::ser::{Serialize, SerializeSeq, Serializer}; 15 16 /// Helper to make a `TinyVec`. 17 /// 18 /// You specify the backing array type, and optionally give all the elements you 19 /// want to initially place into the array. 20 /// 21 /// ```rust 22 /// use tinyvec::*; 23 /// 24 /// // The backing array type can be specified in the macro call 25 /// let empty_tv = tiny_vec!([u8; 16]); 26 /// let some_ints = tiny_vec!([i32; 4] => 1, 2, 3); 27 /// let many_ints = tiny_vec!([i32; 4] => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 28 /// 29 /// // Or left to inference 30 /// let empty_tv: TinyVec<[u8; 16]> = tiny_vec!(); 31 /// let some_ints: TinyVec<[i32; 4]> = tiny_vec!(1, 2, 3); 32 /// let many_ints: TinyVec<[i32; 4]> = tiny_vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 33 /// ``` 34 #[macro_export] 35 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))] 36 macro_rules! tiny_vec { 37 ($array_type:ty => $($elem:expr),* $(,)?) => { 38 { 39 // https://github.com/rust-lang/lang-team/issues/28 40 const INVOKED_ELEM_COUNT: usize = 0 $( + { let _ = stringify!($elem); 1 })*; 41 // If we have more `$elem` than the `CAPACITY` we will simply go directly 42 // to constructing on the heap. 43 match $crate::TinyVec::constructor_for_capacity(INVOKED_ELEM_COUNT) { 44 $crate::TinyVecConstructor::Inline(f) => { 45 f($crate::array_vec!($array_type => $($elem),*)) 46 } 47 $crate::TinyVecConstructor::Heap(f) => { 48 f(vec!($($elem),*)) 49 } 50 } 51 } 52 }; 53 ($array_type:ty) => { 54 $crate::TinyVec::<$array_type>::default() 55 }; 56 ($($elem:expr),*) => { 57 $crate::tiny_vec!(_ => $($elem),*) 58 }; 59 ($elem:expr; $n:expr) => { 60 $crate::TinyVec::from([$elem; $n]) 61 }; 62 () => { 63 $crate::tiny_vec!(_) 64 }; 65 } 66 67 #[doc(hidden)] // Internal implementation details of `tiny_vec!` 68 pub enum TinyVecConstructor<A: Array> { 69 Inline(fn(ArrayVec<A>) -> TinyVec<A>), 70 Heap(fn(Vec<A::Item>) -> TinyVec<A>), 71 } 72 73 /// A vector that starts inline, but can automatically move to the heap. 74 /// 75 /// * Requires the `alloc` feature 76 /// 77 /// A `TinyVec` is either an Inline([`ArrayVec`](crate::ArrayVec::<A>)) or 78 /// Heap([`Vec`](https://doc.rust-lang.org/alloc/vec/struct.Vec.html)). The 79 /// interface for the type as a whole is a bunch of methods that just match on 80 /// the enum variant and then call the same method on the inner vec. 81 /// 82 /// ## Construction 83 /// 84 /// Because it's an enum, you can construct a `TinyVec` simply by making an 85 /// `ArrayVec` or `Vec` and then putting it into the enum. 86 /// 87 /// There is also a macro 88 /// 89 /// ```rust 90 /// # use tinyvec::*; 91 /// let empty_tv = tiny_vec!([u8; 16]); 92 /// let some_ints = tiny_vec!([i32; 4] => 1, 2, 3); 93 /// ``` 94 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))] 95 pub enum TinyVec<A: Array> { 96 #[allow(missing_docs)] 97 Inline(ArrayVec<A>), 98 #[allow(missing_docs)] 99 Heap(Vec<A::Item>), 100 } 101 102 impl<A> Clone for TinyVec<A> 103 where 104 A: Array + Clone, 105 A::Item: Clone, 106 { 107 #[inline] clone(&self) -> Self108 fn clone(&self) -> Self { 109 match self { 110 Self::Heap(v) => Self::Heap(v.clone()), 111 Self::Inline(v) => Self::Inline(v.clone()), 112 } 113 } 114 115 #[inline] clone_from(&mut self, o: &Self)116 fn clone_from(&mut self, o: &Self) { 117 if o.len() > self.len() { 118 self.reserve(o.len() - self.len()); 119 } else { 120 self.truncate(o.len()); 121 } 122 let (start, end) = o.split_at(self.len()); 123 for (dst, src) in self.iter_mut().zip(start) { 124 dst.clone_from(src); 125 } 126 self.extend_from_slice(end); 127 } 128 } 129 130 impl<A: Array> Default for TinyVec<A> { 131 #[inline] 132 #[must_use] default() -> Self133 fn default() -> Self { 134 TinyVec::Inline(ArrayVec::default()) 135 } 136 } 137 138 impl<A: Array> Deref for TinyVec<A> { 139 type Target = [A::Item]; 140 141 impl_mirrored! { 142 type Mirror = TinyVec; 143 #[inline(always)] 144 #[must_use] 145 fn deref(self: &Self) -> &Self::Target; 146 } 147 } 148 149 impl<A: Array> DerefMut for TinyVec<A> { 150 impl_mirrored! { 151 type Mirror = TinyVec; 152 #[inline(always)] 153 #[must_use] 154 fn deref_mut(self: &mut Self) -> &mut Self::Target; 155 } 156 } 157 158 impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for TinyVec<A> { 159 type Output = <I as SliceIndex<[A::Item]>>::Output; 160 #[inline(always)] 161 #[must_use] index(&self, index: I) -> &Self::Output162 fn index(&self, index: I) -> &Self::Output { 163 &self.deref()[index] 164 } 165 } 166 167 impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for TinyVec<A> { 168 #[inline(always)] 169 #[must_use] index_mut(&mut self, index: I) -> &mut Self::Output170 fn index_mut(&mut self, index: I) -> &mut Self::Output { 171 &mut self.deref_mut()[index] 172 } 173 } 174 175 #[cfg(feature = "std")] 176 #[cfg_attr(docs_rs, doc(cfg(feature = "std")))] 177 impl<A: Array<Item = u8>> std::io::Write for TinyVec<A> { 178 #[inline(always)] write(&mut self, buf: &[u8]) -> std::io::Result<usize>179 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { 180 self.extend_from_slice(buf); 181 Ok(buf.len()) 182 } 183 184 #[inline(always)] flush(&mut self) -> std::io::Result<()>185 fn flush(&mut self) -> std::io::Result<()> { 186 Ok(()) 187 } 188 } 189 190 #[cfg(feature = "serde")] 191 #[cfg_attr(docs_rs, doc(cfg(feature = "serde")))] 192 impl<A: Array> Serialize for TinyVec<A> 193 where 194 A::Item: Serialize, 195 { 196 #[must_use] serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,197 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 198 where 199 S: Serializer, 200 { 201 let mut seq = serializer.serialize_seq(Some(self.len()))?; 202 for element in self.iter() { 203 seq.serialize_element(element)?; 204 } 205 seq.end() 206 } 207 } 208 209 #[cfg(feature = "serde")] 210 #[cfg_attr(docs_rs, doc(cfg(feature = "serde")))] 211 impl<'de, A: Array> Deserialize<'de> for TinyVec<A> 212 where 213 A::Item: Deserialize<'de>, 214 { deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,215 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 216 where 217 D: Deserializer<'de>, 218 { 219 deserializer.deserialize_seq(TinyVecVisitor(PhantomData)) 220 } 221 } 222 223 #[cfg(feature = "arbitrary")] 224 #[cfg_attr(docs_rs, doc(cfg(feature = "arbitrary")))] 225 impl<'a, A> arbitrary::Arbitrary<'a> for TinyVec<A> 226 where 227 A: Array, 228 A::Item: arbitrary::Arbitrary<'a>, 229 { arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self>230 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { 231 let v = Vec::arbitrary(u)?; 232 let mut tv = TinyVec::Heap(v); 233 tv.shrink_to_fit(); 234 Ok(tv) 235 } 236 } 237 238 impl<A: Array> TinyVec<A> { 239 /// Returns whether elements are on heap 240 #[inline(always)] 241 #[must_use] is_heap(&self) -> bool242 pub fn is_heap(&self) -> bool { 243 match self { 244 TinyVec::Heap(_) => true, 245 TinyVec::Inline(_) => false, 246 } 247 } 248 /// Returns whether elements are on stack 249 #[inline(always)] 250 #[must_use] is_inline(&self) -> bool251 pub fn is_inline(&self) -> bool { 252 !self.is_heap() 253 } 254 255 /// Shrinks the capacity of the vector as much as possible.\ 256 /// It is inlined if length is less than `A::CAPACITY`. 257 /// ```rust 258 /// use tinyvec::*; 259 /// let mut tv = tiny_vec!([i32; 2] => 1, 2, 3); 260 /// assert!(tv.is_heap()); 261 /// let _ = tv.pop(); 262 /// assert!(tv.is_heap()); 263 /// tv.shrink_to_fit(); 264 /// assert!(tv.is_inline()); 265 /// ``` shrink_to_fit(&mut self)266 pub fn shrink_to_fit(&mut self) { 267 let vec = match self { 268 TinyVec::Inline(_) => return, 269 TinyVec::Heap(h) => h, 270 }; 271 272 if vec.len() > A::CAPACITY { 273 return vec.shrink_to_fit(); 274 } 275 276 let moved_vec = core::mem::replace(vec, Vec::new()); 277 278 let mut av = ArrayVec::default(); 279 let mut rest = av.fill(moved_vec); 280 debug_assert!(rest.next().is_none()); 281 *self = TinyVec::Inline(av); 282 } 283 284 /// Moves the content of the TinyVec to the heap, if it's inline. 285 /// ```rust 286 /// use tinyvec::*; 287 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3); 288 /// assert!(tv.is_inline()); 289 /// tv.move_to_the_heap(); 290 /// assert!(tv.is_heap()); 291 /// ``` 292 #[allow(clippy::missing_inline_in_public_items)] move_to_the_heap(&mut self)293 pub fn move_to_the_heap(&mut self) { 294 let arr = match self { 295 TinyVec::Heap(_) => return, 296 TinyVec::Inline(a) => a, 297 }; 298 299 let v = arr.drain_to_vec(); 300 *self = TinyVec::Heap(v); 301 } 302 303 /// If TinyVec is inline, moves the content of it to the heap. 304 /// Also reserves additional space. 305 /// ```rust 306 /// use tinyvec::*; 307 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3); 308 /// assert!(tv.is_inline()); 309 /// tv.move_to_the_heap_and_reserve(32); 310 /// assert!(tv.is_heap()); 311 /// assert!(tv.capacity() >= 35); 312 /// ``` move_to_the_heap_and_reserve(&mut self, n: usize)313 pub fn move_to_the_heap_and_reserve(&mut self, n: usize) { 314 let arr = match self { 315 TinyVec::Heap(h) => return h.reserve(n), 316 TinyVec::Inline(a) => a, 317 }; 318 319 let v = arr.drain_to_vec_and_reserve(n); 320 *self = TinyVec::Heap(v); 321 } 322 323 /// Reserves additional space. 324 /// Moves to the heap if array can't hold `n` more items 325 /// ```rust 326 /// use tinyvec::*; 327 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3, 4); 328 /// assert!(tv.is_inline()); 329 /// tv.reserve(1); 330 /// assert!(tv.is_heap()); 331 /// assert!(tv.capacity() >= 5); 332 /// ``` reserve(&mut self, n: usize)333 pub fn reserve(&mut self, n: usize) { 334 let arr = match self { 335 TinyVec::Heap(h) => return h.reserve(n), 336 TinyVec::Inline(a) => a, 337 }; 338 339 if n > arr.capacity() - arr.len() { 340 let v = arr.drain_to_vec_and_reserve(n); 341 *self = TinyVec::Heap(v); 342 } 343 344 /* In this place array has enough place, so no work is needed more */ 345 return; 346 } 347 348 /// Reserves additional space. 349 /// Moves to the heap if array can't hold `n` more items 350 /// 351 /// From [Vec::reserve_exact](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve_exact) 352 /// ```text 353 /// Note that the allocator may give the collection more space than it requests. 354 /// Therefore, capacity can not be relied upon to be precisely minimal. 355 /// Prefer `reserve` if future insertions are expected. 356 /// ``` 357 /// ```rust 358 /// use tinyvec::*; 359 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3, 4); 360 /// assert!(tv.is_inline()); 361 /// tv.reserve_exact(1); 362 /// assert!(tv.is_heap()); 363 /// assert!(tv.capacity() >= 5); 364 /// ``` reserve_exact(&mut self, n: usize)365 pub fn reserve_exact(&mut self, n: usize) { 366 let arr = match self { 367 TinyVec::Heap(h) => return h.reserve_exact(n), 368 TinyVec::Inline(a) => a, 369 }; 370 371 if n > arr.capacity() - arr.len() { 372 let v = arr.drain_to_vec_and_reserve(n); 373 *self = TinyVec::Heap(v); 374 } 375 376 /* In this place array has enough place, so no work is needed more */ 377 return; 378 } 379 380 /// Makes a new TinyVec with _at least_ the given capacity. 381 /// 382 /// If the requested capacity is less than or equal to the array capacity you 383 /// get an inline vec. If it's greater than you get a heap vec. 384 /// ``` 385 /// # use tinyvec::*; 386 /// let t = TinyVec::<[u8; 10]>::with_capacity(5); 387 /// assert!(t.is_inline()); 388 /// assert!(t.capacity() >= 5); 389 /// 390 /// let t = TinyVec::<[u8; 10]>::with_capacity(20); 391 /// assert!(t.is_heap()); 392 /// assert!(t.capacity() >= 20); 393 /// ``` 394 #[inline] 395 #[must_use] with_capacity(cap: usize) -> Self396 pub fn with_capacity(cap: usize) -> Self { 397 if cap <= A::CAPACITY { 398 TinyVec::Inline(ArrayVec::default()) 399 } else { 400 TinyVec::Heap(Vec::with_capacity(cap)) 401 } 402 } 403 } 404 405 impl<A: Array> TinyVec<A> { 406 /// Move all values from `other` into this vec. 407 #[cfg(feature = "rustc_1_40")] 408 #[inline] append(&mut self, other: &mut Self)409 pub fn append(&mut self, other: &mut Self) { 410 self.reserve(other.len()); 411 412 /* Doing append should be faster, because it is effectively a memcpy */ 413 match (self, other) { 414 (TinyVec::Heap(sh), TinyVec::Heap(oh)) => sh.append(oh), 415 (TinyVec::Inline(a), TinyVec::Heap(h)) => a.extend(h.drain(..)), 416 (ref mut this, TinyVec::Inline(arr)) => this.extend(arr.drain(..)), 417 } 418 } 419 420 /// Move all values from `other` into this vec. 421 #[cfg(not(feature = "rustc_1_40"))] 422 #[inline] append(&mut self, other: &mut Self)423 pub fn append(&mut self, other: &mut Self) { 424 match other { 425 TinyVec::Inline(a) => self.extend(a.drain(..)), 426 TinyVec::Heap(h) => self.extend(h.drain(..)), 427 } 428 } 429 430 impl_mirrored! { 431 type Mirror = TinyVec; 432 433 /// Remove an element, swapping the end of the vec into its place. 434 /// 435 /// ## Panics 436 /// * If the index is out of bounds. 437 /// 438 /// ## Example 439 /// ```rust 440 /// use tinyvec::*; 441 /// let mut tv = tiny_vec!([&str; 4] => "foo", "bar", "quack", "zap"); 442 /// 443 /// assert_eq!(tv.swap_remove(1), "bar"); 444 /// assert_eq!(tv.as_slice(), &["foo", "zap", "quack"][..]); 445 /// 446 /// assert_eq!(tv.swap_remove(0), "foo"); 447 /// assert_eq!(tv.as_slice(), &["quack", "zap"][..]); 448 /// ``` 449 #[inline] 450 pub fn swap_remove(self: &mut Self, index: usize) -> A::Item; 451 452 /// Remove and return the last element of the vec, if there is one. 453 /// 454 /// ## Failure 455 /// * If the vec is empty you get `None`. 456 #[inline] 457 pub fn pop(self: &mut Self) -> Option<A::Item>; 458 459 /// Removes the item at `index`, shifting all others down by one index. 460 /// 461 /// Returns the removed element. 462 /// 463 /// ## Panics 464 /// 465 /// If the index is out of bounds. 466 /// 467 /// ## Example 468 /// 469 /// ```rust 470 /// use tinyvec::*; 471 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3); 472 /// assert_eq!(tv.remove(1), 2); 473 /// assert_eq!(tv.as_slice(), &[1, 3][..]); 474 /// ``` 475 #[inline] 476 pub fn remove(self: &mut Self, index: usize) -> A::Item; 477 478 /// The length of the vec (in elements). 479 #[inline(always)] 480 #[must_use] 481 pub fn len(self: &Self) -> usize; 482 483 /// The capacity of the `TinyVec`. 484 /// 485 /// When not heap allocated this is fixed based on the array type. 486 /// Otherwise its the result of the underlying Vec::capacity. 487 #[inline(always)] 488 #[must_use] 489 pub fn capacity(self: &Self) -> usize; 490 491 /// Reduces the vec's length to the given value. 492 /// 493 /// If the vec is already shorter than the input, nothing happens. 494 #[inline] 495 pub fn truncate(self: &mut Self, new_len: usize); 496 497 /// A mutable pointer to the backing array. 498 /// 499 /// ## Safety 500 /// 501 /// This pointer has provenance over the _entire_ backing array/buffer. 502 #[inline(always)] 503 #[must_use] 504 pub fn as_mut_ptr(self: &mut Self) -> *mut A::Item; 505 506 /// A const pointer to the backing array. 507 /// 508 /// ## Safety 509 /// 510 /// This pointer has provenance over the _entire_ backing array/buffer. 511 #[inline(always)] 512 #[must_use] 513 pub fn as_ptr(self: &Self) -> *const A::Item; 514 } 515 516 /// Walk the vec and keep only the elements that pass the predicate given. 517 /// 518 /// ## Example 519 /// 520 /// ```rust 521 /// use tinyvec::*; 522 /// 523 /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3, 4); 524 /// tv.retain(|&x| x % 2 == 0); 525 /// assert_eq!(tv.as_slice(), &[2, 4][..]); 526 /// ``` 527 #[inline] retain<F: FnMut(&A::Item) -> bool>(self: &mut Self, acceptable: F)528 pub fn retain<F: FnMut(&A::Item) -> bool>(self: &mut Self, acceptable: F) { 529 match self { 530 TinyVec::Inline(i) => i.retain(acceptable), 531 TinyVec::Heap(h) => h.retain(acceptable), 532 } 533 } 534 535 /// Helper for getting the mut slice. 536 #[inline(always)] 537 #[must_use] as_mut_slice(self: &mut Self) -> &mut [A::Item]538 pub fn as_mut_slice(self: &mut Self) -> &mut [A::Item] { 539 self.deref_mut() 540 } 541 542 /// Helper for getting the shared slice. 543 #[inline(always)] 544 #[must_use] as_slice(self: &Self) -> &[A::Item]545 pub fn as_slice(self: &Self) -> &[A::Item] { 546 self.deref() 547 } 548 549 /// Removes all elements from the vec. 550 #[inline(always)] clear(&mut self)551 pub fn clear(&mut self) { 552 self.truncate(0) 553 } 554 555 /// De-duplicates the vec. 556 #[cfg(feature = "nightly_slice_partition_dedup")] 557 #[inline(always)] dedup(&mut self) where A::Item: PartialEq,558 pub fn dedup(&mut self) 559 where 560 A::Item: PartialEq, 561 { 562 self.dedup_by(|a, b| a == b) 563 } 564 565 /// De-duplicates the vec according to the predicate given. 566 #[cfg(feature = "nightly_slice_partition_dedup")] 567 #[inline(always)] dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut A::Item, &mut A::Item) -> bool,568 pub fn dedup_by<F>(&mut self, same_bucket: F) 569 where 570 F: FnMut(&mut A::Item, &mut A::Item) -> bool, 571 { 572 let len = { 573 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket); 574 dedup.len() 575 }; 576 self.truncate(len); 577 } 578 579 /// De-duplicates the vec according to the key selector given. 580 #[cfg(feature = "nightly_slice_partition_dedup")] 581 #[inline(always)] dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut A::Item) -> K, K: PartialEq,582 pub fn dedup_by_key<F, K>(&mut self, mut key: F) 583 where 584 F: FnMut(&mut A::Item) -> K, 585 K: PartialEq, 586 { 587 self.dedup_by(|a, b| key(a) == key(b)) 588 } 589 590 /// Creates a draining iterator that removes the specified range in the vector 591 /// and yields the removed items. 592 /// 593 /// **Note: This method has significant performance issues compared to 594 /// matching on the TinyVec and then calling drain on the Inline or Heap value 595 /// inside. The draining iterator has to branch on every single access. It is 596 /// provided for simplicity and compatability only.** 597 /// 598 /// ## Panics 599 /// * If the start is greater than the end 600 /// * If the end is past the edge of the vec. 601 /// 602 /// ## Example 603 /// ```rust 604 /// use tinyvec::*; 605 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3); 606 /// let tv2: TinyVec<[i32; 4]> = tv.drain(1..).collect(); 607 /// assert_eq!(tv.as_slice(), &[1][..]); 608 /// assert_eq!(tv2.as_slice(), &[2, 3][..]); 609 /// 610 /// tv.drain(..); 611 /// assert_eq!(tv.as_slice(), &[]); 612 /// ``` 613 #[inline] drain<R: RangeBounds<usize>>( &mut self, range: R, ) -> TinyVecDrain<'_, A>614 pub fn drain<R: RangeBounds<usize>>( 615 &mut self, range: R, 616 ) -> TinyVecDrain<'_, A> { 617 match self { 618 TinyVec::Inline(i) => TinyVecDrain::Inline(i.drain(range)), 619 TinyVec::Heap(h) => TinyVecDrain::Heap(h.drain(range)), 620 } 621 } 622 623 /// Clone each element of the slice into this vec. 624 /// ```rust 625 /// use tinyvec::*; 626 /// let mut tv = tiny_vec!([i32; 4] => 1, 2); 627 /// tv.extend_from_slice(&[3, 4]); 628 /// assert_eq!(tv.as_slice(), [1, 2, 3, 4]); 629 /// ``` 630 #[inline] extend_from_slice(&mut self, sli: &[A::Item]) where A::Item: Clone,631 pub fn extend_from_slice(&mut self, sli: &[A::Item]) 632 where 633 A::Item: Clone, 634 { 635 self.reserve(sli.len()); 636 match self { 637 TinyVec::Inline(a) => a.extend_from_slice(sli), 638 TinyVec::Heap(h) => h.extend_from_slice(sli), 639 } 640 } 641 642 /// Wraps up an array and uses the given length as the initial length. 643 /// 644 /// Note that the `From` impl for arrays assumes the full length is used. 645 /// 646 /// ## Panics 647 /// 648 /// The length must be less than or equal to the capacity of the array. 649 #[inline] 650 #[must_use] 651 #[allow(clippy::match_wild_err_arm)] from_array_len(data: A, len: usize) -> Self652 pub fn from_array_len(data: A, len: usize) -> Self { 653 match Self::try_from_array_len(data, len) { 654 Ok(out) => out, 655 Err(_) => { 656 panic!("TinyVec: length {} exceeds capacity {}!", len, A::CAPACITY) 657 } 658 } 659 } 660 661 /// This is an internal implementation detail of the `tiny_vec!` macro, and 662 /// using it other than from that macro is not supported by this crate's 663 /// SemVer guarantee. 664 #[inline(always)] 665 #[doc(hidden)] constructor_for_capacity(cap: usize) -> TinyVecConstructor<A>666 pub fn constructor_for_capacity(cap: usize) -> TinyVecConstructor<A> { 667 if cap <= A::CAPACITY { 668 TinyVecConstructor::Inline(TinyVec::Inline) 669 } else { 670 TinyVecConstructor::Heap(TinyVec::Heap) 671 } 672 } 673 674 /// Inserts an item at the position given, moving all following elements +1 675 /// index. 676 /// 677 /// ## Panics 678 /// * If `index` > `len` 679 /// 680 /// ## Example 681 /// ```rust 682 /// use tinyvec::*; 683 /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3); 684 /// tv.insert(1, 4); 685 /// assert_eq!(tv.as_slice(), &[1, 4, 2, 3]); 686 /// tv.insert(4, 5); 687 /// assert_eq!(tv.as_slice(), &[1, 4, 2, 3, 5]); 688 /// ``` 689 #[inline] insert(&mut self, index: usize, item: A::Item)690 pub fn insert(&mut self, index: usize, item: A::Item) { 691 assert!( 692 index <= self.len(), 693 "insertion index (is {}) should be <= len (is {})", 694 index, 695 self.len() 696 ); 697 698 let arr = match self { 699 TinyVec::Heap(v) => return v.insert(index, item), 700 TinyVec::Inline(a) => a, 701 }; 702 703 if let Some(x) = arr.try_insert(index, item) { 704 let mut v = Vec::with_capacity(arr.len() * 2); 705 let mut it = 706 arr.iter_mut().map(|r| core::mem::replace(r, Default::default())); 707 v.extend(it.by_ref().take(index)); 708 v.push(x); 709 v.extend(it); 710 *self = TinyVec::Heap(v); 711 } 712 } 713 714 /// If the vec is empty. 715 #[inline(always)] 716 #[must_use] is_empty(&self) -> bool717 pub fn is_empty(&self) -> bool { 718 self.len() == 0 719 } 720 721 /// Makes a new, empty vec. 722 #[inline(always)] 723 #[must_use] new() -> Self724 pub fn new() -> Self { 725 Self::default() 726 } 727 728 /// Place an element onto the end of the vec. 729 /// ## Panics 730 /// * If the length of the vec would overflow the capacity. 731 /// ```rust 732 /// use tinyvec::*; 733 /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3); 734 /// tv.push(4); 735 /// assert_eq!(tv.as_slice(), &[1, 2, 3, 4]); 736 /// ``` 737 #[inline] push(&mut self, val: A::Item)738 pub fn push(&mut self, val: A::Item) { 739 // The code path for moving the inline contents to the heap produces a lot 740 // of instructions, but we have a strong guarantee that this is a cold 741 // path. LLVM doesn't know this, inlines it, and this tends to cause a 742 // cascade of other bad inlining decisions because the body of push looks 743 // huge even though nearly every call executes the same few instructions. 744 // 745 // Moving the logic out of line with #[cold] causes the hot code to be 746 // inlined together, and we take the extra cost of a function call only 747 // in rare cases. 748 #[cold] 749 fn drain_to_heap_and_push<A: Array>( 750 arr: &mut ArrayVec<A>, val: A::Item, 751 ) -> TinyVec<A> { 752 /* Make the Vec twice the size to amortize the cost of draining */ 753 let mut v = arr.drain_to_vec_and_reserve(arr.len()); 754 v.push(val); 755 TinyVec::Heap(v) 756 } 757 758 match self { 759 TinyVec::Heap(v) => v.push(val), 760 TinyVec::Inline(arr) => { 761 if let Some(x) = arr.try_push(val) { 762 *self = drain_to_heap_and_push(arr, x); 763 } 764 } 765 } 766 } 767 768 /// Resize the vec to the new length. 769 /// 770 /// If it needs to be longer, it's filled with clones of the provided value. 771 /// If it needs to be shorter, it's truncated. 772 /// 773 /// ## Example 774 /// 775 /// ```rust 776 /// use tinyvec::*; 777 /// 778 /// let mut tv = tiny_vec!([&str; 10] => "hello"); 779 /// tv.resize(3, "world"); 780 /// assert_eq!(tv.as_slice(), &["hello", "world", "world"][..]); 781 /// 782 /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3, 4); 783 /// tv.resize(2, 0); 784 /// assert_eq!(tv.as_slice(), &[1, 2][..]); 785 /// ``` 786 #[inline] resize(&mut self, new_len: usize, new_val: A::Item) where A::Item: Clone,787 pub fn resize(&mut self, new_len: usize, new_val: A::Item) 788 where 789 A::Item: Clone, 790 { 791 self.resize_with(new_len, || new_val.clone()); 792 } 793 794 /// Resize the vec to the new length. 795 /// 796 /// If it needs to be longer, it's filled with repeated calls to the provided 797 /// function. If it needs to be shorter, it's truncated. 798 /// 799 /// ## Example 800 /// 801 /// ```rust 802 /// use tinyvec::*; 803 /// 804 /// let mut tv = tiny_vec!([i32; 3] => 1, 2, 3); 805 /// tv.resize_with(5, Default::default); 806 /// assert_eq!(tv.as_slice(), &[1, 2, 3, 0, 0][..]); 807 /// 808 /// let mut tv = tiny_vec!([i32; 2]); 809 /// let mut p = 1; 810 /// tv.resize_with(4, || { 811 /// p *= 2; 812 /// p 813 /// }); 814 /// assert_eq!(tv.as_slice(), &[2, 4, 8, 16][..]); 815 /// ``` 816 #[inline] resize_with<F: FnMut() -> A::Item>(&mut self, new_len: usize, f: F)817 pub fn resize_with<F: FnMut() -> A::Item>(&mut self, new_len: usize, f: F) { 818 match new_len.checked_sub(self.len()) { 819 None => return self.truncate(new_len), 820 Some(n) => self.reserve(n), 821 } 822 823 match self { 824 TinyVec::Inline(a) => a.resize_with(new_len, f), 825 TinyVec::Heap(v) => v.resize_with(new_len, f), 826 } 827 } 828 829 /// Splits the collection at the point given. 830 /// 831 /// * `[0, at)` stays in this vec 832 /// * `[at, len)` ends up in the new vec. 833 /// 834 /// ## Panics 835 /// * if at > len 836 /// 837 /// ## Example 838 /// 839 /// ```rust 840 /// use tinyvec::*; 841 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3); 842 /// let tv2 = tv.split_off(1); 843 /// assert_eq!(tv.as_slice(), &[1][..]); 844 /// assert_eq!(tv2.as_slice(), &[2, 3][..]); 845 /// ``` 846 #[inline] split_off(&mut self, at: usize) -> Self847 pub fn split_off(&mut self, at: usize) -> Self { 848 match self { 849 TinyVec::Inline(a) => TinyVec::Inline(a.split_off(at)), 850 TinyVec::Heap(v) => TinyVec::Heap(v.split_off(at)), 851 } 852 } 853 854 /// Creates a splicing iterator that removes the specified range in the 855 /// vector, yields the removed items, and replaces them with elements from 856 /// the provided iterator. 857 /// 858 /// `splice` fuses the provided iterator, so elements after the first `None` 859 /// are ignored. 860 /// 861 /// ## Panics 862 /// * If the start is greater than the end. 863 /// * If the end is past the edge of the vec. 864 /// * If the provided iterator panics. 865 /// 866 /// ## Example 867 /// ```rust 868 /// use tinyvec::*; 869 /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3); 870 /// let tv2: TinyVec<[i32; 4]> = tv.splice(1.., 4..=6).collect(); 871 /// assert_eq!(tv.as_slice(), &[1, 4, 5, 6][..]); 872 /// assert_eq!(tv2.as_slice(), &[2, 3][..]); 873 /// 874 /// tv.splice(.., None); 875 /// assert_eq!(tv.as_slice(), &[]); 876 /// ``` 877 #[inline] splice<R, I>( &mut self, range: R, replacement: I, ) -> TinyVecSplice<'_, A, core::iter::Fuse<I::IntoIter>> where R: RangeBounds<usize>, I: IntoIterator<Item = A::Item>,878 pub fn splice<R, I>( 879 &mut self, range: R, replacement: I, 880 ) -> TinyVecSplice<'_, A, core::iter::Fuse<I::IntoIter>> 881 where 882 R: RangeBounds<usize>, 883 I: IntoIterator<Item = A::Item>, 884 { 885 use core::ops::Bound; 886 let start = match range.start_bound() { 887 Bound::Included(x) => *x, 888 Bound::Excluded(x) => x.saturating_add(1), 889 Bound::Unbounded => 0, 890 }; 891 let end = match range.end_bound() { 892 Bound::Included(x) => x.saturating_add(1), 893 Bound::Excluded(x) => *x, 894 Bound::Unbounded => self.len(), 895 }; 896 assert!( 897 start <= end, 898 "TinyVec::splice> Illegal range, {} to {}", 899 start, 900 end 901 ); 902 assert!( 903 end <= self.len(), 904 "TinyVec::splice> Range ends at {} but length is only {}!", 905 end, 906 self.len() 907 ); 908 909 TinyVecSplice { 910 removal_start: start, 911 removal_end: end, 912 parent: self, 913 replacement: replacement.into_iter().fuse(), 914 } 915 } 916 917 /// Wraps an array, using the given length as the starting length. 918 /// 919 /// If you want to use the whole length of the array, you can just use the 920 /// `From` impl. 921 /// 922 /// ## Failure 923 /// 924 /// If the given length is greater than the capacity of the array this will 925 /// error, and you'll get the array back in the `Err`. 926 #[inline] try_from_array_len(data: A, len: usize) -> Result<Self, A>927 pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> { 928 let arr = ArrayVec::try_from_array_len(data, len)?; 929 Ok(TinyVec::Inline(arr)) 930 } 931 } 932 933 /// Draining iterator for `TinyVecDrain` 934 /// 935 /// See [`TinyVecDrain::drain`](TinyVecDrain::<A>::drain) 936 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))] 937 pub enum TinyVecDrain<'p, A: Array> { 938 #[allow(missing_docs)] 939 Inline(ArrayVecDrain<'p, A::Item>), 940 #[allow(missing_docs)] 941 Heap(vec::Drain<'p, A::Item>), 942 } 943 944 impl<'p, A: Array> Iterator for TinyVecDrain<'p, A> { 945 type Item = A::Item; 946 947 impl_mirrored! { 948 type Mirror = TinyVecDrain; 949 950 #[inline] 951 fn next(self: &mut Self) -> Option<Self::Item>; 952 #[inline] 953 fn nth(self: &mut Self, n: usize) -> Option<Self::Item>; 954 #[inline] 955 fn size_hint(self: &Self) -> (usize, Option<usize>); 956 #[inline] 957 fn last(self: Self) -> Option<Self::Item>; 958 #[inline] 959 fn count(self: Self) -> usize; 960 } 961 962 #[inline] for_each<F: FnMut(Self::Item)>(self, f: F)963 fn for_each<F: FnMut(Self::Item)>(self, f: F) { 964 match self { 965 TinyVecDrain::Inline(i) => i.for_each(f), 966 TinyVecDrain::Heap(h) => h.for_each(f), 967 } 968 } 969 } 970 971 impl<'p, A: Array> DoubleEndedIterator for TinyVecDrain<'p, A> { 972 impl_mirrored! { 973 type Mirror = TinyVecDrain; 974 975 #[inline] 976 fn next_back(self: &mut Self) -> Option<Self::Item>; 977 978 #[cfg(feature = "rustc_1_40")] 979 #[inline] 980 fn nth_back(self: &mut Self, n: usize) -> Option<Self::Item>; 981 } 982 } 983 984 /// Splicing iterator for `TinyVec` 985 /// See [`TinyVec::splice`](TinyVec::<A>::splice) 986 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))] 987 pub struct TinyVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> { 988 parent: &'p mut TinyVec<A>, 989 removal_start: usize, 990 removal_end: usize, 991 replacement: I, 992 } 993 994 impl<'p, A, I> Iterator for TinyVecSplice<'p, A, I> 995 where 996 A: Array, 997 I: Iterator<Item = A::Item>, 998 { 999 type Item = A::Item; 1000 1001 #[inline] next(&mut self) -> Option<A::Item>1002 fn next(&mut self) -> Option<A::Item> { 1003 if self.removal_start < self.removal_end { 1004 match self.replacement.next() { 1005 Some(replacement) => { 1006 let removed = core::mem::replace( 1007 &mut self.parent[self.removal_start], 1008 replacement, 1009 ); 1010 self.removal_start += 1; 1011 Some(removed) 1012 } 1013 None => { 1014 let removed = self.parent.remove(self.removal_start); 1015 self.removal_end -= 1; 1016 Some(removed) 1017 } 1018 } 1019 } else { 1020 None 1021 } 1022 } 1023 1024 #[inline] size_hint(&self) -> (usize, Option<usize>)1025 fn size_hint(&self) -> (usize, Option<usize>) { 1026 let len = self.len(); 1027 (len, Some(len)) 1028 } 1029 } 1030 1031 impl<'p, A, I> ExactSizeIterator for TinyVecSplice<'p, A, I> 1032 where 1033 A: Array, 1034 I: Iterator<Item = A::Item>, 1035 { 1036 #[inline] len(&self) -> usize1037 fn len(&self) -> usize { 1038 self.removal_end - self.removal_start 1039 } 1040 } 1041 1042 impl<'p, A, I> FusedIterator for TinyVecSplice<'p, A, I> 1043 where 1044 A: Array, 1045 I: Iterator<Item = A::Item>, 1046 { 1047 } 1048 1049 impl<'p, A, I> DoubleEndedIterator for TinyVecSplice<'p, A, I> 1050 where 1051 A: Array, 1052 I: Iterator<Item = A::Item> + DoubleEndedIterator, 1053 { 1054 #[inline] next_back(&mut self) -> Option<A::Item>1055 fn next_back(&mut self) -> Option<A::Item> { 1056 if self.removal_start < self.removal_end { 1057 match self.replacement.next_back() { 1058 Some(replacement) => { 1059 let removed = core::mem::replace( 1060 &mut self.parent[self.removal_end - 1], 1061 replacement, 1062 ); 1063 self.removal_end -= 1; 1064 Some(removed) 1065 } 1066 None => { 1067 let removed = self.parent.remove(self.removal_end - 1); 1068 self.removal_end -= 1; 1069 Some(removed) 1070 } 1071 } 1072 } else { 1073 None 1074 } 1075 } 1076 } 1077 1078 impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop 1079 for TinyVecSplice<'p, A, I> 1080 { drop(&mut self)1081 fn drop(&mut self) { 1082 for _ in self.by_ref() {} 1083 1084 let (lower_bound, _) = self.replacement.size_hint(); 1085 self.parent.reserve(lower_bound); 1086 1087 for replacement in self.replacement.by_ref() { 1088 self.parent.insert(self.removal_end, replacement); 1089 self.removal_end += 1; 1090 } 1091 } 1092 } 1093 1094 impl<A: Array> AsMut<[A::Item]> for TinyVec<A> { 1095 #[inline(always)] 1096 #[must_use] as_mut(&mut self) -> &mut [A::Item]1097 fn as_mut(&mut self) -> &mut [A::Item] { 1098 &mut *self 1099 } 1100 } 1101 1102 impl<A: Array> AsRef<[A::Item]> for TinyVec<A> { 1103 #[inline(always)] 1104 #[must_use] as_ref(&self) -> &[A::Item]1105 fn as_ref(&self) -> &[A::Item] { 1106 &*self 1107 } 1108 } 1109 1110 impl<A: Array> Borrow<[A::Item]> for TinyVec<A> { 1111 #[inline(always)] 1112 #[must_use] borrow(&self) -> &[A::Item]1113 fn borrow(&self) -> &[A::Item] { 1114 &*self 1115 } 1116 } 1117 1118 impl<A: Array> BorrowMut<[A::Item]> for TinyVec<A> { 1119 #[inline(always)] 1120 #[must_use] borrow_mut(&mut self) -> &mut [A::Item]1121 fn borrow_mut(&mut self) -> &mut [A::Item] { 1122 &mut *self 1123 } 1124 } 1125 1126 impl<A: Array> Extend<A::Item> for TinyVec<A> { 1127 #[inline] extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T)1128 fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) { 1129 let iter = iter.into_iter(); 1130 let (lower_bound, _) = iter.size_hint(); 1131 self.reserve(lower_bound); 1132 1133 let a = match self { 1134 TinyVec::Heap(h) => return h.extend(iter), 1135 TinyVec::Inline(a) => a, 1136 }; 1137 1138 let mut iter = a.fill(iter); 1139 let maybe = iter.next(); 1140 1141 let surely = match maybe { 1142 Some(x) => x, 1143 None => return, 1144 }; 1145 1146 let mut v = a.drain_to_vec_and_reserve(a.len()); 1147 v.push(surely); 1148 v.extend(iter); 1149 *self = TinyVec::Heap(v); 1150 } 1151 } 1152 1153 impl<A: Array> From<ArrayVec<A>> for TinyVec<A> { 1154 #[inline(always)] 1155 #[must_use] from(arr: ArrayVec<A>) -> Self1156 fn from(arr: ArrayVec<A>) -> Self { 1157 TinyVec::Inline(arr) 1158 } 1159 } 1160 1161 impl<A: Array> From<A> for TinyVec<A> { from(array: A) -> Self1162 fn from(array: A) -> Self { 1163 TinyVec::Inline(ArrayVec::from(array)) 1164 } 1165 } 1166 1167 impl<T, A> From<&'_ [T]> for TinyVec<A> 1168 where 1169 T: Clone + Default, 1170 A: Array<Item = T>, 1171 { 1172 #[inline] 1173 #[must_use] from(slice: &[T]) -> Self1174 fn from(slice: &[T]) -> Self { 1175 if let Ok(arr) = ArrayVec::try_from(slice) { 1176 TinyVec::Inline(arr) 1177 } else { 1178 TinyVec::Heap(slice.into()) 1179 } 1180 } 1181 } 1182 1183 impl<T, A> From<&'_ mut [T]> for TinyVec<A> 1184 where 1185 T: Clone + Default, 1186 A: Array<Item = T>, 1187 { 1188 #[inline] 1189 #[must_use] from(slice: &mut [T]) -> Self1190 fn from(slice: &mut [T]) -> Self { 1191 Self::from(&*slice) 1192 } 1193 } 1194 1195 impl<A: Array> FromIterator<A::Item> for TinyVec<A> { 1196 #[inline] 1197 #[must_use] from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self1198 fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self { 1199 let mut av = Self::default(); 1200 av.extend(iter); 1201 av 1202 } 1203 } 1204 1205 /// Iterator for consuming an `TinyVec` and returning owned elements. 1206 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))] 1207 pub enum TinyVecIterator<A: Array> { 1208 #[allow(missing_docs)] 1209 Inline(ArrayVecIterator<A>), 1210 #[allow(missing_docs)] 1211 Heap(alloc::vec::IntoIter<A::Item>), 1212 } 1213 1214 impl<A: Array> TinyVecIterator<A> { 1215 impl_mirrored! { 1216 type Mirror = TinyVecIterator; 1217 /// Returns the remaining items of this iterator as a slice. 1218 #[inline] 1219 #[must_use] 1220 pub fn as_slice(self: &Self) -> &[A::Item]; 1221 } 1222 } 1223 1224 impl<A: Array> FusedIterator for TinyVecIterator<A> {} 1225 1226 impl<A: Array> Iterator for TinyVecIterator<A> { 1227 type Item = A::Item; 1228 1229 impl_mirrored! { 1230 type Mirror = TinyVecIterator; 1231 1232 #[inline] 1233 fn next(self: &mut Self) -> Option<Self::Item>; 1234 1235 #[inline(always)] 1236 #[must_use] 1237 fn size_hint(self: &Self) -> (usize, Option<usize>); 1238 1239 #[inline(always)] 1240 fn count(self: Self) -> usize; 1241 1242 #[inline] 1243 fn last(self: Self) -> Option<Self::Item>; 1244 1245 #[inline] 1246 fn nth(self: &mut Self, n: usize) -> Option<A::Item>; 1247 } 1248 } 1249 1250 impl<A: Array> DoubleEndedIterator for TinyVecIterator<A> { 1251 impl_mirrored! { 1252 type Mirror = TinyVecIterator; 1253 1254 #[inline] 1255 fn next_back(self: &mut Self) -> Option<Self::Item>; 1256 1257 #[cfg(feature = "rustc_1_40")] 1258 #[inline] 1259 fn nth_back(self: &mut Self, n: usize) -> Option<Self::Item>; 1260 } 1261 } 1262 1263 impl<A: Array> Debug for TinyVecIterator<A> 1264 where 1265 A::Item: Debug, 1266 { 1267 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result1268 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { 1269 f.debug_tuple("TinyVecIterator").field(&self.as_slice()).finish() 1270 } 1271 } 1272 1273 impl<A: Array> IntoIterator for TinyVec<A> { 1274 type Item = A::Item; 1275 type IntoIter = TinyVecIterator<A>; 1276 #[inline(always)] 1277 #[must_use] into_iter(self) -> Self::IntoIter1278 fn into_iter(self) -> Self::IntoIter { 1279 match self { 1280 TinyVec::Inline(a) => TinyVecIterator::Inline(a.into_iter()), 1281 TinyVec::Heap(v) => TinyVecIterator::Heap(v.into_iter()), 1282 } 1283 } 1284 } 1285 1286 impl<'a, A: Array> IntoIterator for &'a mut TinyVec<A> { 1287 type Item = &'a mut A::Item; 1288 type IntoIter = core::slice::IterMut<'a, A::Item>; 1289 #[inline(always)] 1290 #[must_use] into_iter(self) -> Self::IntoIter1291 fn into_iter(self) -> Self::IntoIter { 1292 self.iter_mut() 1293 } 1294 } 1295 1296 impl<'a, A: Array> IntoIterator for &'a TinyVec<A> { 1297 type Item = &'a A::Item; 1298 type IntoIter = core::slice::Iter<'a, A::Item>; 1299 #[inline(always)] 1300 #[must_use] into_iter(self) -> Self::IntoIter1301 fn into_iter(self) -> Self::IntoIter { 1302 self.iter() 1303 } 1304 } 1305 1306 impl<A: Array> PartialEq for TinyVec<A> 1307 where 1308 A::Item: PartialEq, 1309 { 1310 #[inline] 1311 #[must_use] eq(&self, other: &Self) -> bool1312 fn eq(&self, other: &Self) -> bool { 1313 self.as_slice().eq(other.as_slice()) 1314 } 1315 } 1316 impl<A: Array> Eq for TinyVec<A> where A::Item: Eq {} 1317 1318 impl<A: Array> PartialOrd for TinyVec<A> 1319 where 1320 A::Item: PartialOrd, 1321 { 1322 #[inline] 1323 #[must_use] partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering>1324 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { 1325 self.as_slice().partial_cmp(other.as_slice()) 1326 } 1327 } 1328 impl<A: Array> Ord for TinyVec<A> 1329 where 1330 A::Item: Ord, 1331 { 1332 #[inline] 1333 #[must_use] cmp(&self, other: &Self) -> core::cmp::Ordering1334 fn cmp(&self, other: &Self) -> core::cmp::Ordering { 1335 self.as_slice().cmp(other.as_slice()) 1336 } 1337 } 1338 1339 impl<A: Array> PartialEq<&A> for TinyVec<A> 1340 where 1341 A::Item: PartialEq, 1342 { 1343 #[inline] 1344 #[must_use] eq(&self, other: &&A) -> bool1345 fn eq(&self, other: &&A) -> bool { 1346 self.as_slice().eq(other.as_slice()) 1347 } 1348 } 1349 1350 impl<A: Array> PartialEq<&[A::Item]> for TinyVec<A> 1351 where 1352 A::Item: PartialEq, 1353 { 1354 #[inline] 1355 #[must_use] eq(&self, other: &&[A::Item]) -> bool1356 fn eq(&self, other: &&[A::Item]) -> bool { 1357 self.as_slice().eq(*other) 1358 } 1359 } 1360 1361 impl<A: Array> Hash for TinyVec<A> 1362 where 1363 A::Item: Hash, 1364 { 1365 #[inline] hash<H: Hasher>(&self, state: &mut H)1366 fn hash<H: Hasher>(&self, state: &mut H) { 1367 self.as_slice().hash(state) 1368 } 1369 } 1370 1371 // // // // // // // // 1372 // Formatting impls 1373 // // // // // // // // 1374 1375 impl<A: Array> Binary for TinyVec<A> 1376 where 1377 A::Item: Binary, 1378 { 1379 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1380 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1381 write!(f, "[")?; 1382 if f.alternate() { 1383 write!(f, "\n ")?; 1384 } 1385 for (i, elem) in self.iter().enumerate() { 1386 if i > 0 { 1387 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1388 } 1389 Binary::fmt(elem, f)?; 1390 } 1391 if f.alternate() { 1392 write!(f, ",\n")?; 1393 } 1394 write!(f, "]") 1395 } 1396 } 1397 1398 impl<A: Array> Debug for TinyVec<A> 1399 where 1400 A::Item: Debug, 1401 { 1402 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1403 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1404 write!(f, "[")?; 1405 if f.alternate() { 1406 write!(f, "\n ")?; 1407 } 1408 for (i, elem) in self.iter().enumerate() { 1409 if i > 0 { 1410 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1411 } 1412 Debug::fmt(elem, f)?; 1413 } 1414 if f.alternate() { 1415 write!(f, ",\n")?; 1416 } 1417 write!(f, "]") 1418 } 1419 } 1420 1421 impl<A: Array> Display for TinyVec<A> 1422 where 1423 A::Item: Display, 1424 { 1425 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1426 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1427 write!(f, "[")?; 1428 if f.alternate() { 1429 write!(f, "\n ")?; 1430 } 1431 for (i, elem) in self.iter().enumerate() { 1432 if i > 0 { 1433 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1434 } 1435 Display::fmt(elem, f)?; 1436 } 1437 if f.alternate() { 1438 write!(f, ",\n")?; 1439 } 1440 write!(f, "]") 1441 } 1442 } 1443 1444 impl<A: Array> LowerExp for TinyVec<A> 1445 where 1446 A::Item: LowerExp, 1447 { 1448 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1449 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1450 write!(f, "[")?; 1451 if f.alternate() { 1452 write!(f, "\n ")?; 1453 } 1454 for (i, elem) in self.iter().enumerate() { 1455 if i > 0 { 1456 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1457 } 1458 LowerExp::fmt(elem, f)?; 1459 } 1460 if f.alternate() { 1461 write!(f, ",\n")?; 1462 } 1463 write!(f, "]") 1464 } 1465 } 1466 1467 impl<A: Array> LowerHex for TinyVec<A> 1468 where 1469 A::Item: LowerHex, 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 if f.alternate() { 1475 write!(f, "\n ")?; 1476 } 1477 for (i, elem) in self.iter().enumerate() { 1478 if i > 0 { 1479 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1480 } 1481 LowerHex::fmt(elem, f)?; 1482 } 1483 if f.alternate() { 1484 write!(f, ",\n")?; 1485 } 1486 write!(f, "]") 1487 } 1488 } 1489 1490 impl<A: Array> Octal for TinyVec<A> 1491 where 1492 A::Item: Octal, 1493 { 1494 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1495 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1496 write!(f, "[")?; 1497 if f.alternate() { 1498 write!(f, "\n ")?; 1499 } 1500 for (i, elem) in self.iter().enumerate() { 1501 if i > 0 { 1502 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1503 } 1504 Octal::fmt(elem, f)?; 1505 } 1506 if f.alternate() { 1507 write!(f, ",\n")?; 1508 } 1509 write!(f, "]") 1510 } 1511 } 1512 1513 impl<A: Array> Pointer for TinyVec<A> 1514 where 1515 A::Item: Pointer, 1516 { 1517 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1518 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1519 write!(f, "[")?; 1520 if f.alternate() { 1521 write!(f, "\n ")?; 1522 } 1523 for (i, elem) in self.iter().enumerate() { 1524 if i > 0 { 1525 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1526 } 1527 Pointer::fmt(elem, f)?; 1528 } 1529 if f.alternate() { 1530 write!(f, ",\n")?; 1531 } 1532 write!(f, "]") 1533 } 1534 } 1535 1536 impl<A: Array> UpperExp for TinyVec<A> 1537 where 1538 A::Item: UpperExp, 1539 { 1540 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1541 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1542 write!(f, "[")?; 1543 if f.alternate() { 1544 write!(f, "\n ")?; 1545 } 1546 for (i, elem) in self.iter().enumerate() { 1547 if i > 0 { 1548 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1549 } 1550 UpperExp::fmt(elem, f)?; 1551 } 1552 if f.alternate() { 1553 write!(f, ",\n")?; 1554 } 1555 write!(f, "]") 1556 } 1557 } 1558 1559 impl<A: Array> UpperHex for TinyVec<A> 1560 where 1561 A::Item: UpperHex, 1562 { 1563 #[allow(clippy::missing_inline_in_public_items)] fmt(&self, f: &mut Formatter) -> core::fmt::Result1564 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { 1565 write!(f, "[")?; 1566 if f.alternate() { 1567 write!(f, "\n ")?; 1568 } 1569 for (i, elem) in self.iter().enumerate() { 1570 if i > 0 { 1571 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; 1572 } 1573 UpperHex::fmt(elem, f)?; 1574 } 1575 if f.alternate() { 1576 write!(f, ",\n")?; 1577 } 1578 write!(f, "]") 1579 } 1580 } 1581 1582 #[cfg(feature = "serde")] 1583 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))] 1584 struct TinyVecVisitor<A: Array>(PhantomData<A>); 1585 1586 #[cfg(feature = "serde")] 1587 impl<'de, A: Array> Visitor<'de> for TinyVecVisitor<A> 1588 where 1589 A::Item: Deserialize<'de>, 1590 { 1591 type Value = TinyVec<A>; 1592 expecting( &self, formatter: &mut core::fmt::Formatter, ) -> core::fmt::Result1593 fn expecting( 1594 &self, formatter: &mut core::fmt::Formatter, 1595 ) -> core::fmt::Result { 1596 formatter.write_str("a sequence") 1597 } 1598 visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error> where S: SeqAccess<'de>,1599 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error> 1600 where 1601 S: SeqAccess<'de>, 1602 { 1603 let mut new_tinyvec = match seq.size_hint() { 1604 Some(expected_size) => TinyVec::with_capacity(expected_size), 1605 None => Default::default(), 1606 }; 1607 1608 while let Some(value) = seq.next_element()? { 1609 new_tinyvec.push(value); 1610 } 1611 1612 Ok(new_tinyvec) 1613 } 1614 } 1615