Create a draining iterator that removes the specified range in the vector and yields the removed items from start to end. The element range is removed even if the iterator is not consumed until the end. Note: It is unspecified how many elements are removed from the vector, if the `Drain` value is leaked. Panics** if the starting point is greater than the end point or if the end point is greater
(&mut self, range: R)
| 264 | /// **Panics** if the starting point is greater than the end point or if |
| 265 | /// the end point is greater than the length of the vector. |
| 266 | pub fn drain<R>(&mut self, range: R) -> Drain<'_, T> |
| 267 | where |
| 268 | R: RangeBounds<usize>, |
| 269 | { |
| 270 | // Memory safety |
| 271 | // |
| 272 | // When the Drain is first created, it shortens the length of |
| 273 | // the source vector to make sure no uninitialized or moved-from elements |
| 274 | // are accessible at all if the Drain's destructor never gets to run. |
| 275 | // |
| 276 | // Drain will ptr::read out the values to remove. |
| 277 | // When finished, remaining tail of the vec is copied back to cover |
| 278 | // the hole, and the vector length is restored to the new length. |
| 279 | // |
| 280 | let len = self.len(); |
| 281 | let start = match range.start_bound() { |
| 282 | Bound::Unbounded => 0, |
| 283 | Bound::Included(&i) => i, |
| 284 | Bound::Excluded(&i) => i.saturating_add(1), |
| 285 | }; |
| 286 | let end = match range.end_bound() { |
| 287 | Bound::Excluded(&j) => j, |
| 288 | Bound::Included(&j) => j.saturating_add(1), |
| 289 | Bound::Unbounded => len, |
| 290 | }; |
| 291 | self.drain_range(start, end) |
| 292 | } |
| 293 | |
| 294 | fn drain_range(&mut self, start: usize, end: usize) -> Drain<'_, T> { |
| 295 | let len = self.len(); |