@@ -567,6 +567,58 @@ impl<T, const N: usize> Vec<T, N> {
567
567
let ( v, n) = ( self . len ( ) , needle. len ( ) ) ;
568
568
v >= n && needle == & self [ v - n..]
569
569
}
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
+ }
570
622
}
571
623
572
624
// Trait implementations
0 commit comments