MCPcopy Create free account
hub / github.com/Lokathor/tinyvec / try_insert

Method try_insert

src/arrayvec.rs:593–622  ·  view source on GitHub ↗
(
    &mut self, index: usize, mut item: A::Item,
  )

Source from the content-addressed store, hash-verified

591 /// ```
592 #[inline]
593 pub fn try_insert(
594 &mut self, index: usize, mut item: A::Item,
595 ) -> Option<A::Item> {
596 assert!(
597 index <= self.len as usize,
598 "ArrayVec::try_insert> index {} is out of bounds {}",
599 index,
600 self.len
601 );
602
603 // A previous implementation used self.try_push and slice::rotate_right
604 // rotate_right and rotate_left generate a huge amount of code and fail to
605 // inline; calling them here incurs the cost of all the cases they
606 // handle even though we're rotating a usually-small array by a constant
607 // 1 offset. This swap-based implementation benchmarks much better for
608 // small array lengths in particular.
609
610 if (self.len as usize) < A::CAPACITY {
611 self.len += 1;
612 } else {
613 return Some(item);
614 }
615
616 let target = &mut self.as_mut_slice()[index..];
617 #[allow(clippy::needless_range_loop)]
618 for i in 0..target.len() {
619 core::mem::swap(&mut item, &mut target[i]);
620 }
621 return None;
622 }
623
624 /// Checks if the length is 0.
625 #[inline(always)]

Callers 2

insertMethod · 0.80
insertMethod · 0.80

Calls 2

as_mut_sliceMethod · 0.45
lenMethod · 0.45

Tested by

no test coverage detected