Skip to content

Commit 5c39282

Browse files
committed
out_of_bounds_indexing refactoring
1 parent 0f3345e commit 5c39282

File tree

1 file changed

+30
-35
lines changed

1 file changed

+30
-35
lines changed

clippy_lints/src/indexing_slicing.rs

Lines changed: 30 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -108,46 +108,41 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing {
108108
if let ExprKind::Index(ref array, ref index) = &expr.node {
109109
let ty = cx.tables.expr_ty(array);
110110
if let Some(range) = higher::range(cx, index) {
111+
111112
// Ranged indexes, i.e. &x[n..m], &x[n..], &x[..n] and &x[..]
112113
if let ty::Array(_, s) = ty.sty {
113114
let size: u128 = s.assert_usize(cx.tcx).unwrap().into();
114115

115-
match to_const_range(cx, range, size) {
116-
(None, None) => {},
117-
(Some(start), None) => {
118-
if start > size {
119-
utils::span_lint(
120-
cx,
121-
OUT_OF_BOUNDS_INDEXING,
122-
expr.span,
123-
"range is out of bounds",
124-
);
125-
return;
126-
}
127-
},
128-
(None, Some(end)) => {
129-
if end > size {
130-
utils::span_lint(
131-
cx,
132-
OUT_OF_BOUNDS_INDEXING,
133-
expr.span,
134-
"range is out of bounds",
135-
);
136-
return;
137-
}
138-
},
139-
(Some(start), Some(end)) => {
140-
if start > size || end > size {
141-
utils::span_lint(
142-
cx,
143-
OUT_OF_BOUNDS_INDEXING,
144-
expr.span,
145-
"range is out of bounds",
146-
);
147-
}
148-
// early return because both start and end are constant
116+
let const_range = to_const_range(cx, range, size);
117+
118+
if let (Some(start), _) = const_range {
119+
if start > size {
120+
utils::span_lint(
121+
cx,
122+
OUT_OF_BOUNDS_INDEXING,
123+
expr.span,
124+
"range is out of bounds",
125+
);
126+
return;
127+
}
128+
}
129+
130+
if let (_, Some(end)) = const_range {
131+
if end > size {
132+
utils::span_lint(
133+
cx,
134+
OUT_OF_BOUNDS_INDEXING,
135+
expr.span,
136+
"range is out of bounds",
137+
);
149138
return;
150-
},
139+
}
140+
}
141+
142+
if let (Some(_), Some(_)) = const_range {
143+
// early return because both start and end are constants
144+
// and we have proven above that they are in bounds
145+
return;
151146
}
152147
}
153148

0 commit comments

Comments
 (0)