Coverage Report

Created: 2024-12-17 06:15

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