about summary refs log tree commit diff
path: root/library/alloc/src
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2020-09-04 12:21:43 +0000
committerbors <bors@rust-lang.org>2020-09-04 12:21:43 +0000
commitef55a0a92f3cb6572ef67d99f4aefbdeb7b6b804 (patch)
treef811be6020731d8ff158e0e4d6b0265c9662370d /library/alloc/src
parent4ffb5c5954a304daf47a567b34e74e421db86d98 (diff)
parentd9e877fb98212a47dd425e145b8b3e4283e6b487 (diff)
downloadrust-ef55a0a92f3cb6572ef67d99f4aefbdeb7b6b804.tar.gz
rust-ef55a0a92f3cb6572ef67d99f4aefbdeb7b6b804.zip
Auto merge of #75207 - dylni:add-slice-check-range, r=KodrAus
Add `slice::check_range`

This method is useful for [`RangeBounds`] parameters. It's even been [rewritten](https://github.com/rust-lang/rust/blob/22ee68dc586440f96b76b32fbd6087507c6afdb9/src/librustc_data_structures/sorted_map.rs#L214) [many](https://github.com/rust-lang/rust/blob/22ee68dc586440f96b76b32fbd6087507c6afdb9/library/alloc/src/vec.rs#L1299) [times](https://github.com/rust-lang/rust/blob/22ee68dc586440f96b76b32fbd6087507c6afdb9/library/core/src/slice/mod.rs#L2441) in the standard library, sometimes assuming that the bounds won't be [`usize::MAX`].

For example, [`Vec::drain`] creates an empty iterator when [`usize::MAX`] is used as an inclusive end bound:

```rust
assert!(vec![1].drain(..=usize::max_value()).eq(iter::empty()));
```

If this PR is merged, I'll create another to use it for those methods.

[`RangeBounds`]: https://doc.rust-lang.org/std/ops/trait.RangeBounds.html
[`usize::MAX`]: https://doc.rust-lang.org/std/primitive.usize.html#associatedconstant.MAX
[`Vec::drain`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.drain
Diffstat (limited to 'library/alloc/src')
-rw-r--r--library/alloc/src/collections/vec_deque.rs39
-rw-r--r--library/alloc/src/lib.rs1
-rw-r--r--library/alloc/src/string.rs20
-rw-r--r--library/alloc/src/vec.rs33
4 files changed, 22 insertions, 71 deletions
diff --git a/library/alloc/src/collections/vec_deque.rs b/library/alloc/src/collections/vec_deque.rs
index 52b9f73ba88..cc2ef25a5a7 100644
--- a/library/alloc/src/collections/vec_deque.rs
+++ b/library/alloc/src/collections/vec_deque.rs
@@ -14,8 +14,7 @@ use core::fmt;
 use core::hash::{Hash, Hasher};
 use core::iter::{once, repeat_with, FromIterator, FusedIterator};
 use core::mem::{self, replace, ManuallyDrop};
-use core::ops::Bound::{Excluded, Included, Unbounded};
-use core::ops::{Index, IndexMut, RangeBounds, Try};
+use core::ops::{Index, IndexMut, Range, RangeBounds, Try};
 use core::ptr::{self, NonNull};
 use core::slice;
 
@@ -1090,24 +1089,18 @@ impl<T> VecDeque<T> {
         self.tail == self.head
     }
 
-    fn range_start_end<R>(&self, range: R) -> (usize, usize)
+    fn range_tail_head<R>(&self, range: R) -> (usize, usize)
     where
         R: RangeBounds<usize>,
     {
-        let len = self.len();
-        let start = match range.start_bound() {
-            Included(&n) => n,
-            Excluded(&n) => n + 1,
-            Unbounded => 0,
-        };
-        let end = match range.end_bound() {
-            Included(&n) => n + 1,
-            Excluded(&n) => n,
-            Unbounded => len,
-        };
-        assert!(start <= end, "lower bound was too large");
-        assert!(end <= len, "upper bound was too large");
-        (start, end)
+        // SAFETY: This buffer is only used to check the range. It might be partially
+        // uninitialized, but `check_range` needs a contiguous slice.
+        // https://github.com/rust-lang/rust/pull/75207#discussion_r471193682
+        let buffer = unsafe { slice::from_raw_parts(self.ptr(), self.len()) };
+        let Range { start, end } = buffer.check_range(range);
+        let tail = self.wrap_add(self.tail, start);
+        let head = self.wrap_add(self.tail, end);
+        (tail, head)
     }
 
     /// Creates an iterator that covers the specified range in the `VecDeque`.
@@ -1138,9 +1131,7 @@ impl<T> VecDeque<T> {
     where
         R: RangeBounds<usize>,
     {
-        let (start, end) = self.range_start_end(range);
-        let tail = self.wrap_add(self.tail, start);
-        let head = self.wrap_add(self.tail, end);
+        let (tail, head) = self.range_tail_head(range);
         Iter {
             tail,
             head,
@@ -1181,9 +1172,7 @@ impl<T> VecDeque<T> {
     where
         R: RangeBounds<usize>,
     {
-        let (start, end) = self.range_start_end(range);
-        let tail = self.wrap_add(self.tail, start);
-        let head = self.wrap_add(self.tail, end);
+        let (tail, head) = self.range_tail_head(range);
         IterMut {
             tail,
             head,
@@ -1237,7 +1226,7 @@ impl<T> VecDeque<T> {
         // When finished, the remaining data will be copied back to cover the hole,
         // and the head/tail values will be restored correctly.
         //
-        let (start, end) = self.range_start_end(range);
+        let (drain_tail, drain_head) = self.range_tail_head(range);
 
         // The deque's elements are parted into three segments:
         // * self.tail  -> drain_tail
@@ -1255,8 +1244,6 @@ impl<T> VecDeque<T> {
         //        T   t   h   H
         // [. . . o o x x o o . . .]
         //
-        let drain_tail = self.wrap_add(self.tail, start);
-        let drain_head = self.wrap_add(self.tail, end);
         let head = self.head;
 
         // "forget" about the values after the start of the drain until after
diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs
index 43b70a51636..2ced10831e7 100644
--- a/library/alloc/src/lib.rs
+++ b/library/alloc/src/lib.rs
@@ -119,6 +119,7 @@
 #![feature(rustc_attrs)]
 #![feature(receiver_trait)]
 #![feature(min_specialization)]
+#![feature(slice_check_range)]
 #![feature(slice_ptr_get)]
 #![feature(slice_ptr_len)]
 #![feature(staged_api)]
diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs
index 05690e19d23..e1724bf3c9a 100644
--- a/library/alloc/src/string.rs
+++ b/library/alloc/src/string.rs
@@ -47,7 +47,7 @@ use core::fmt;
 use core::hash;
 use core::iter::{FromIterator, FusedIterator};
 use core::ops::Bound::{Excluded, Included, Unbounded};
-use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
+use core::ops::{self, Add, AddAssign, Index, IndexMut, Range, RangeBounds};
 use core::ptr;
 use core::str::{lossy, pattern::Pattern};
 
@@ -1506,23 +1506,15 @@ impl String {
         // of the vector version. The data is just plain bytes.
         // Because the range removal happens in Drop, if the Drain iterator is leaked,
         // the removal will not happen.
-        let len = self.len();
-        let start = match range.start_bound() {
-            Included(&n) => n,
-            Excluded(&n) => n + 1,
-            Unbounded => 0,
-        };
-        let end = match range.end_bound() {
-            Included(&n) => n + 1,
-            Excluded(&n) => n,
-            Unbounded => len,
-        };
+        let Range { start, end } = self.as_bytes().check_range(range);
+        assert!(self.is_char_boundary(start));
+        assert!(self.is_char_boundary(end));
 
         // Take out two simultaneous borrows. The &mut String won't be accessed
         // until iteration is over, in Drop.
         let self_ptr = self as *mut _;
-        // slicing does the appropriate bounds checks
-        let chars_iter = self[start..end].chars();
+        // SAFETY: `check_range` and `is_char_boundary` do the appropriate bounds checks.
+        let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
 
         Drain { start, end, iter: chars_iter, string: self_ptr }
     }
diff --git a/library/alloc/src/vec.rs b/library/alloc/src/vec.rs
index 9013e3fc16a..6a4fc8e3962 100644
--- a/library/alloc/src/vec.rs
+++ b/library/alloc/src/vec.rs
@@ -63,8 +63,7 @@ use core::iter::{
 };
 use core::marker::PhantomData;
 use core::mem::{self, ManuallyDrop, MaybeUninit};
-use core::ops::Bound::{Excluded, Included, Unbounded};
-use core::ops::{self, Index, IndexMut, RangeBounds};
+use core::ops::{self, Index, IndexMut, Range, RangeBounds};
 use core::ptr::{self, NonNull};
 use core::slice::{self, SliceIndex};
 
@@ -1306,35 +1305,7 @@ impl<T> Vec<T> {
         // the hole, and the vector length is restored to the new length.
         //
         let len = self.len();
-        let start = match range.start_bound() {
-            Included(&n) => n,
-            Excluded(&n) => n + 1,
-            Unbounded => 0,
-        };
-        let end = match range.end_bound() {
-            Included(&n) => n + 1,
-            Excluded(&n) => n,
-            Unbounded => len,
-        };
-
-        #[cold]
-        #[inline(never)]
-        fn start_assert_failed(start: usize, end: usize) -> ! {
-            panic!("start drain index (is {}) should be <= end drain index (is {})", start, end);
-        }
-
-        #[cold]
-        #[inline(never)]
-        fn end_assert_failed(end: usize, len: usize) -> ! {
-            panic!("end drain index (is {}) should be <= len (is {})", end, len);
-        }
-
-        if start > end {
-            start_assert_failed(start, end);
-        }
-        if end > len {
-            end_assert_failed(end, len);
-        }
+        let Range { start, end } = self.check_range(range);
 
         unsafe {
             // set self.vec length's to start, to be safe in case Drain is leaked