Skip to content

Commit 67d1708

Browse files
committed
string_slice should detect on Cow
1 parent 5da97d0 commit 67d1708

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

clippy_lints/src/strings.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ impl<'tcx> LateLintPass<'tcx> for StringAdd {
191191
},
192192
ExprKind::Index(target, _idx, _) => {
193193
let e_ty = cx.typeck_results().expr_ty(target).peel_refs();
194-
if e_ty.is_str() || is_type_lang_item(cx, e_ty, LangItem::String) {
194+
if e_ty.is_str() || is_type_lang_item(cx, e_ty, LangItem::String) || is_ref_str(cx, target) {
195195
span_lint(
196196
cx,
197197
STRING_SLICE,
@@ -205,6 +205,13 @@ impl<'tcx> LateLintPass<'tcx> for StringAdd {
205205
}
206206
}
207207

208+
fn is_ref_str(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
209+
match cx.typeck_results().expr_ty_adjusted(expr).kind() {
210+
ty::Ref(_, ty, _) => ty.is_str(),
211+
_ => false,
212+
}
213+
}
214+
208215
fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
209216
is_type_lang_item(cx, cx.typeck_results().expr_ty(e).peel_refs(), LangItem::String)
210217
}

tests/ui/string_slice.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::borrow::Cow;
2+
13
#[warn(clippy::string_slice)]
24
#[allow(clippy::no_effect)]
35

@@ -11,4 +13,6 @@ fn main() {
1113
let s = String::from(m);
1214
&s[0..2];
1315
//~^ ERROR: indexing into a string may panic if the index is within a UTF-8 character
16+
let a = Cow::Borrowed("foo");
17+
&a[0..3];
1418
}

tests/ui/string_slice.stderr

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: indexing into a string may panic if the index is within a UTF-8 character
2-
--> tests/ui/string_slice.rs:5:6
2+
--> tests/ui/string_slice.rs:7:6
33
|
44
LL | &"Ölkanne"[1..];
55
| ^^^^^^^^^^^^^^
@@ -8,16 +8,22 @@ LL | &"Ölkanne"[1..];
88
= help: to override `-D warnings` add `#[allow(clippy::string_slice)]`
99

1010
error: indexing into a string may panic if the index is within a UTF-8 character
11-
--> tests/ui/string_slice.rs:9:6
11+
--> tests/ui/string_slice.rs:11:6
1212
|
1313
LL | &m[2..5];
1414
| ^^^^^^^
1515

1616
error: indexing into a string may panic if the index is within a UTF-8 character
17-
--> tests/ui/string_slice.rs:12:6
17+
--> tests/ui/string_slice.rs:14:6
1818
|
1919
LL | &s[0..2];
2020
| ^^^^^^^
2121

22-
error: aborting due to 3 previous errors
22+
error: indexing into a string may panic if the index is within a UTF-8 character
23+
--> tests/ui/string_slice.rs:17:6
24+
|
25+
LL | &a[0..3];
26+
| ^^^^^^^
27+
28+
error: aborting due to 4 previous errors
2329

0 commit comments

Comments
 (0)