Skip to content

Commit fedce67

Browse files
committed
Vec: add insert.
1 parent 344629e commit fedce67

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/vec.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,58 @@ impl<T, const N: usize> Vec<T, N> {
567567
let (v, n) = (self.len(), needle.len());
568568
v >= n && needle == &self[v - n..]
569569
}
570+
571+
/// Inserts an element at position `index` within the vector, shifting all
572+
/// elements after it to the right.
573+
///
574+
/// Returns back the `element` if the vector is full.
575+
///
576+
/// # Panics
577+
///
578+
/// Panics if `index > len`.
579+
///
580+
/// # Examples
581+
///
582+
/// ```
583+
/// use heapless::Vec;
584+
///
585+
/// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
586+
/// vec.insert(1, 4);
587+
/// assert_eq!(vec, [1, 4, 2, 3]);
588+
/// vec.insert(4, 5);
589+
/// assert_eq!(vec, [1, 4, 2, 3, 5]);
590+
/// ```
591+
pub fn insert(&mut self, index: usize, element: T) -> Result<(), T> {
592+
let len = self.len();
593+
if index > len {
594+
panic!(
595+
"insertion index (is {}) should be <= len (is {})",
596+
index, len
597+
);
598+
}
599+
600+
// check there's space for the new element
601+
if self.is_full() {
602+
return Err(element);
603+
}
604+
605+
unsafe {
606+
// infallible
607+
// The spot to put the new value
608+
{
609+
let p = self.as_mut_ptr().add(index);
610+
// Shift everything over to make space. (Duplicating the
611+
// `index`th element into two consecutive places.)
612+
ptr::copy(p, p.offset(1), len - index);
613+
// Write it in, overwriting the first copy of the `index`th
614+
// element.
615+
ptr::write(p, element);
616+
}
617+
self.set_len(len + 1);
618+
}
619+
620+
Ok(())
621+
}
570622
}
571623

572624
// Trait implementations

0 commit comments

Comments
 (0)