2929use core:: ops:: Bound ;
3030use core:: ops:: RangeBounds ;
3131
32+ fn slice_start_and_end < T , R : RangeBounds < usize > > ( slice : & [ T ] , range : R ) -> ( usize , usize ) {
33+ let start = match range. start_bound ( ) {
34+ Bound :: Included ( & n) => n,
35+ Bound :: Excluded ( & n) => n. checked_add ( 1 ) . expect ( "range bound overflows usize" ) ,
36+ Bound :: Unbounded => 0 ,
37+ } ;
38+ let end = match range. end_bound ( ) {
39+ Bound :: Included ( & n) => n. checked_add ( 1 ) . expect ( "range bound overflows usize" ) ,
40+ Bound :: Excluded ( & n) => n,
41+ Bound :: Unbounded => slice. len ( ) ,
42+ } ;
43+ ( start, end)
44+ }
45+
46+ fn get_range < T , R : RangeBounds < usize > > ( slice : & [ T ] , range : R ) -> & [ T ] {
47+ let ( start, end) = slice_start_and_end ( slice, range) ;
48+ & slice[ start..end]
49+ }
50+
51+ // fn get_range_mut<T, R: RangeBounds<usize>>(slice: &mut [T], range: R) -> &mut [T] {
52+ // let (start, end) = slice_start_and_end(slice, range);
53+ // &mut slice[start..end]
54+ // }
55+
3256/// Copies elements from one part of a slice to another part of the same
3357/// slice, using a memmove.
3458///
@@ -55,25 +79,13 @@ use core::ops::RangeBounds;
5579/// assert_eq!(&bytes, b"Hello, Wello!");
5680/// ```
5781pub fn copy_in_place < T : Copy , R : RangeBounds < usize > > ( slice : & mut [ T ] , src : R , dest : usize ) {
58- let src_start = match src. start_bound ( ) {
59- Bound :: Included ( & n) => n,
60- Bound :: Excluded ( & n) => n. checked_add ( 1 ) . expect ( "range bound overflows usize" ) ,
61- Bound :: Unbounded => 0 ,
62- } ;
63- let src_end = match src. end_bound ( ) {
64- Bound :: Included ( & n) => n. checked_add ( 1 ) . expect ( "range bound overflows usize" ) ,
65- Bound :: Excluded ( & n) => n,
66- Bound :: Unbounded => slice. len ( ) ,
82+ let ( src_ptr, src_len) = {
83+ let src_slice = get_range ( slice, src) ;
84+ ( src_slice. as_ptr ( ) , src_slice. len ( ) )
6785 } ;
68- assert ! ( src_start <= src_end, "src end is before src start" ) ;
69- assert ! ( src_end <= slice. len( ) , "src is out of bounds" ) ;
70- let count = src_end - src_start;
71- assert ! ( dest <= slice. len( ) - count, "dest is out of bounds" ) ;
86+ assert ! ( dest <= slice. len( ) - src_len, "dest is out of bounds" ) ;
7287 unsafe {
73- core:: ptr:: copy (
74- slice. get_unchecked ( src_start) ,
75- slice. get_unchecked_mut ( dest) ,
76- count,
77- ) ;
88+ let dest_ptr = slice. as_mut_ptr ( ) . add ( dest) ;
89+ core:: ptr:: copy ( src_ptr, dest_ptr, src_len) ;
7890 }
7991}
0 commit comments