]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/vec_deque/ring_slices.rs
Rollup merge of #90851 - ibraheemdev:downcast-unchecked, r=scottmcm
[rust.git] / library / alloc / src / collections / vec_deque / ring_slices.rs
1 use core::ptr::{self};
2
3 /// Returns the two slices that cover the `VecDeque`'s valid range
4 pub trait RingSlices: Sized {
5     fn slice(self, from: usize, to: usize) -> Self;
6     fn split_at(self, i: usize) -> (Self, Self);
7
8     fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
9         let contiguous = tail <= head;
10         if contiguous {
11             let (empty, buf) = buf.split_at(0);
12             (buf.slice(tail, head), empty)
13         } else {
14             let (mid, right) = buf.split_at(tail);
15             let (left, _) = mid.split_at(head);
16             (right, left)
17         }
18     }
19 }
20
21 impl<T> RingSlices for &[T] {
22     fn slice(self, from: usize, to: usize) -> Self {
23         &self[from..to]
24     }
25     fn split_at(self, i: usize) -> (Self, Self) {
26         (*self).split_at(i)
27     }
28 }
29
30 impl<T> RingSlices for &mut [T] {
31     fn slice(self, from: usize, to: usize) -> Self {
32         &mut self[from..to]
33     }
34     fn split_at(self, i: usize) -> (Self, Self) {
35         (*self).split_at_mut(i)
36     }
37 }
38
39 impl<T> RingSlices for *mut [T] {
40     fn slice(self, from: usize, to: usize) -> Self {
41         assert!(from <= to && to < self.len());
42         // Not using `get_unchecked_mut` to keep this a safe operation.
43         let len = to - from;
44         ptr::slice_from_raw_parts_mut(self.as_mut_ptr().wrapping_add(from), len)
45     }
46
47     fn split_at(self, mid: usize) -> (Self, Self) {
48         let len = self.len();
49         let ptr = self.as_mut_ptr();
50         assert!(mid <= len);
51         (
52             ptr::slice_from_raw_parts_mut(ptr, mid),
53             ptr::slice_from_raw_parts_mut(ptr.wrapping_add(mid), len - mid),
54         )
55     }
56 }