@@ -80,6 +80,7 @@ mod single_char_insert_string;
80
80
mod single_char_pattern;
81
81
mod single_char_push_string;
82
82
mod skip_while_next;
83
+ mod slice_as_bytes;
83
84
mod stable_sort_primitive;
84
85
mod str_splitn;
85
86
mod string_extend_chars;
@@ -3284,6 +3285,27 @@ declare_clippy_lint! {
3284
3285
"calling `.drain(..).collect()` to move all elements into a new collection"
3285
3286
}
3286
3287
3288
+ declare_clippy_lint ! {
3289
+ /// ### What it does
3290
+ /// Checks for string slices immediantly followed by `as_bytes`.
3291
+ /// ### Why is this bad?
3292
+ /// It involves doing an unnecessary UTF-8 alignment check which is less efficient, and can cause a panic.
3293
+ /// ### Example
3294
+ /// ```rust
3295
+ /// let s = "Lorem ipsum";
3296
+ /// s[1..5].as_bytes();
3297
+ /// ```
3298
+ /// Use instead:
3299
+ /// ```rust
3300
+ /// let s = "Lorem ipsum";
3301
+ /// &s.as_bytes()[1..5];
3302
+ /// ```
3303
+ #[ clippy:: version = "1.72.0" ]
3304
+ pub SLICE_AS_BYTES ,
3305
+ perf,
3306
+ "slicing a string and immediately calling as_bytes is less efficient and can lead to panics"
3307
+ }
3308
+
3287
3309
pub struct Methods {
3288
3310
avoid_breaking_exported_api : bool ,
3289
3311
msrv : Msrv ,
@@ -3414,7 +3436,8 @@ impl_lint_pass!(Methods => [
3414
3436
CLEAR_WITH_DRAIN ,
3415
3437
MANUAL_NEXT_BACK ,
3416
3438
UNNECESSARY_LITERAL_UNWRAP ,
3417
- DRAIN_COLLECT
3439
+ DRAIN_COLLECT ,
3440
+ SLICE_AS_BYTES ,
3418
3441
] ) ;
3419
3442
3420
3443
/// Extracts a method call name, args, and `Span` of the method name.
@@ -3623,6 +3646,9 @@ impl Methods {
3623
3646
( "arg" , [ arg] ) => {
3624
3647
suspicious_command_arg_space:: check ( cx, recv, arg, span) ;
3625
3648
}
3649
+ ( "as_bytes" , [ ] ) => {
3650
+ slice_as_bytes:: check ( cx, expr, recv) ;
3651
+ }
3626
3652
( "as_deref" | "as_deref_mut" , [ ] ) => {
3627
3653
needless_option_as_deref:: check ( cx, expr, recv, name) ;
3628
3654
} ,
0 commit comments