@@ -102,6 +102,7 @@ mod single_char_add_str;
102
102
mod single_char_insert_string;
103
103
mod single_char_push_string;
104
104
mod skip_while_next;
105
+ mod sliced_string_as_bytes;
105
106
mod stable_sort_primitive;
106
107
mod str_split;
107
108
mod str_splitn;
@@ -4363,6 +4364,34 @@ declare_clippy_lint! {
4363
4364
"detect `repeat().take()` that can be replaced with `repeat_n()`"
4364
4365
}
4365
4366
4367
+ declare_clippy_lint ! {
4368
+ /// ### What it does
4369
+ /// Checks for string slices immediantly followed by `as_bytes`.
4370
+ ///
4371
+ /// ### Why is this bad?
4372
+ /// It involves doing an unnecessary UTF-8 alignment check which is less efficient, and can cause a panic.
4373
+ ///
4374
+ /// ### Known problems
4375
+ /// In some cases, the UTF-8 validation and potential panic from string slicing may be required for
4376
+ /// the code's correctness. If you need to ensure the slice boundaries fall on valid UTF-8 character
4377
+ /// boundaries, the original form (`s[1..5].as_bytes()`) should be preferred.
4378
+ ///
4379
+ /// ### Example
4380
+ /// ```rust
4381
+ /// let s = "Lorem ipsum";
4382
+ /// s[1..5].as_bytes();
4383
+ /// ```
4384
+ /// Use instead:
4385
+ /// ```rust
4386
+ /// let s = "Lorem ipsum";
4387
+ /// &s.as_bytes()[1..5];
4388
+ /// ```
4389
+ #[ clippy:: version = "1.86.0" ]
4390
+ pub SLICED_STRING_AS_BYTES ,
4391
+ perf,
4392
+ "slicing a string and immediately calling as_bytes is less efficient and can lead to panics"
4393
+ }
4394
+
4366
4395
pub struct Methods {
4367
4396
avoid_breaking_exported_api : bool ,
4368
4397
msrv : Msrv ,
@@ -4531,6 +4560,7 @@ impl_lint_pass!(Methods => [
4531
4560
DOUBLE_ENDED_ITERATOR_LAST ,
4532
4561
USELESS_NONZERO_NEW_UNCHECKED ,
4533
4562
MANUAL_REPEAT_N ,
4563
+ SLICED_STRING_AS_BYTES ,
4534
4564
] ) ;
4535
4565
4536
4566
/// Extracts a method call name, args, and `Span` of the method name.
@@ -4798,6 +4828,7 @@ impl Methods {
4798
4828
if let Some ( ( "as_str" , recv, [ ] , as_str_span, _) ) = method_call ( recv) {
4799
4829
redundant_as_str:: check ( cx, expr, recv, as_str_span, span) ;
4800
4830
}
4831
+ sliced_string_as_bytes:: check ( cx, expr, recv) ;
4801
4832
} ,
4802
4833
( "as_mut" , [ ] ) => useless_asref:: check ( cx, expr, "as_mut" , recv) ,
4803
4834
( "as_ptr" , [ ] ) => manual_c_str_literals:: check_as_ptr ( cx, expr, recv, & self . msrv ) ,
0 commit comments