From da620420013c133528d2b600946f7e2180e9cc5d Mon Sep 17 00:00:00 2001 From: bluss Date: Sun, 30 Jul 2017 13:18:50 +0200 Subject: [PATCH] FEAT: Make swap_remove return the element, add try_swap_remove for fallible --- src/lib.rs | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 41ccbd4..f68130c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -329,25 +329,48 @@ impl ArrayVec { /// /// This operation is O(1). /// - /// Return `Some(` *element* `)` if the index is in bounds, else `None`. + /// Return *element* if the index is in bound, else panic. + /// + /// ***Panics*** if the `index` is out of bounds. /// /// ``` /// use arrayvec::ArrayVec; /// /// let mut array = ArrayVec::from([1, 2, 3]); /// - /// assert_eq!(array.swap_remove(0), Some(1)); + /// assert_eq!(array.swap_remove(0), 1); /// assert_eq!(&array[..], &[3, 2]); /// - /// assert_eq!(array.swap_remove(10), None); + /// assert_eq!(array.swap_remove(1), 2); + /// assert_eq!(&array[..], &[3]); /// ``` - pub fn swap_remove(&mut self, index: usize) -> Option { + pub fn swap_remove(&mut self, index: usize) -> A::Item { + self.try_swap_remove(index).unwrap() + } + + /// Remove the element at `index` and swap the last element into its place. + /// + /// This operation is O(1). + /// + /// Return `Ok(` *element* `)` if the index is in bounds, else an error. + /// + /// ``` + /// use arrayvec::ArrayVec; + /// + /// let mut array = ArrayVec::from([1, 2, 3]); + /// + /// assert!(array.try_swap_remove(0).is_ok()); + /// assert_eq!(&array[..], &[3, 2]); + /// + /// assert!(array.try_swap_remove(10).is_err()); + /// ``` + pub fn try_swap_remove(&mut self, index: usize) -> Result { let len = self.len(); if index >= len { - return None + return Err(RemoveError::new()) } self.swap(index, len - 1); - self.pop() + self.pop().ok_or_else(|| panic!()) } /// Remove the element at `index` and shift down the following elements.