@@ -10,12 +10,19 @@ Add "panic-safe" or "total" alternatives to the existing panicking indexing synt
10
10
# Motivation
11
11
12
12
` SliceExt::get ` and ` SliceExt::get_mut ` can be thought as non-panicking versions of the simple
13
- indexing syntax, ` a[idx] ` . However, there is no such equivalent for ` a[start..end] ` , ` a[start..] ` ,
14
- or ` a[..end] ` . This RFC proposes such methods to fill the gap.
13
+ indexing syntax, ` a[idx] ` , and ` SliceExt::get_unchecked ` and ` SliceExt::get_unchecked_mut ` can
14
+ be thought of as unsafe versions with bounds checks elided. However, there is no such equivalent for
15
+ ` a[start..end] ` , ` a[start..] ` , or ` a[..end] ` . This RFC proposes such methods to fill the gap.
15
16
16
17
# Detailed design
17
18
18
- Introduce a ` SliceIndex ` trait which is implemented by types which can index into a slice:
19
+ The ` get ` , ` get_mut ` , ` get_unchecked ` , and ` get_unchecked_mut ` will be made generic over ` usize `
20
+ as well as ranges of ` usize ` like slice's ` Index ` implementation currently is. This will allow e.g.
21
+ ` a.get(start..end) ` which will behave analagously to ` a[start..end] ` .
22
+
23
+ Because methods cannot be overloaded in an ad-hoc manner in the same way that traits may be
24
+ implemented, we introduce a ` SliceIndex ` trait which is implemented by types which can index into a
25
+ slice:
19
26
``` rust
20
27
pub trait SliceIndex <T > {
21
28
type Output : ? Sized ;
@@ -24,6 +31,8 @@ pub trait SliceIndex<T> {
24
31
fn get_mut (self , slice : & mut [T ]) -> Option <& mut Self :: Output >;
25
32
unsafe fn get_unchecked (self , slice : & [T ]) -> & Self :: Output ;
26
33
unsafe fn get_mut_unchecked (self , slice : & [T ]) -> & mut Self :: Output ;
34
+ fn index (self , slice : & [T ]) -> & Self :: Output ;
35
+ fn index_mut (self , slice : & mut [T ]) -> & mut Self :: Output ;
27
36
}
28
37
29
38
impl <T > SliceIndex <T > for usize {
@@ -39,7 +48,7 @@ impl<T, R> SliceIndex<T> for R
39
48
}
40
49
```
41
50
42
- Alter the ` Index ` , ` IndexMut ` , ` get ` , ` get_mut ` , ` get_unchecked ` , and ` get_mut_unchecked `
51
+ And then alter the ` Index ` , ` IndexMut ` , ` get ` , ` get_mut ` , ` get_unchecked ` , and ` get_mut_unchecked `
43
52
implementations to be generic over ` SliceIndex ` :
44
53
``` rust
45
54
impl <T > [T ] {
@@ -74,15 +83,15 @@ impl<T, I> Index<I> for [T]
74
83
type Output = I :: Output ;
75
84
76
85
fn index (& self , idx : I ) -> & I :: Output {
77
- self . get ( idx ) . expect ( " out of bounds slice access " )
86
+ idx . index ( self )
78
87
}
79
88
}
80
89
81
90
impl <T , I > IndexMut <I > for [T ]
82
91
where I : SliceIndex <T >
83
92
{
84
93
fn index_mut (& self , idx : I ) -> & mut I :: Output {
85
- self . get_mut ( idx ) . expect ( " out of bounds slice access " )
94
+ idx . index_mut ( self )
86
95
}
87
96
}
88
97
```
0 commit comments