29
29
use core:: ops:: Bound ;
30
30
use core:: ops:: RangeBounds ;
31
31
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
+
32
56
/// Copies elements from one part of a slice to another part of the same
33
57
/// slice, using a memmove.
34
58
///
@@ -55,25 +79,13 @@ use core::ops::RangeBounds;
55
79
/// assert_eq!(&bytes, b"Hello, Wello!");
56
80
/// ```
57
81
pub 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 ( ) )
67
85
} ;
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" ) ;
72
87
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) ;
78
90
}
79
91
}
0 commit comments