@@ -102,6 +102,7 @@ mod single_char_add_str;
102102mod single_char_insert_string;
103103mod single_char_push_string;
104104mod skip_while_next;
105+ mod sliced_string_as_bytes;
105106mod stable_sort_primitive;
106107mod str_split;
107108mod str_splitn;
@@ -4363,6 +4364,34 @@ declare_clippy_lint! {
43634364 "detect `repeat().take()` that can be replaced with `repeat_n()`"
43644365}
43654366
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+
43664395pub struct Methods {
43674396 avoid_breaking_exported_api : bool ,
43684397 msrv : Msrv ,
@@ -4531,6 +4560,7 @@ impl_lint_pass!(Methods => [
45314560 DOUBLE_ENDED_ITERATOR_LAST ,
45324561 USELESS_NONZERO_NEW_UNCHECKED ,
45334562 MANUAL_REPEAT_N ,
4563+ SLICED_STRING_AS_BYTES ,
45344564] ) ;
45354565
45364566/// Extracts a method call name, args, and `Span` of the method name.
@@ -4798,6 +4828,7 @@ impl Methods {
47984828 if let Some ( ( "as_str" , recv, [ ] , as_str_span, _) ) = method_call ( recv) {
47994829 redundant_as_str:: check ( cx, expr, recv, as_str_span, span) ;
48004830 }
4831+ sliced_string_as_bytes:: check ( cx, expr, recv) ;
48014832 } ,
48024833 ( "as_mut" , [ ] ) => useless_asref:: check ( cx, expr, "as_mut" , recv) ,
48034834 ( "as_ptr" , [ ] ) => manual_c_str_literals:: check_as_ptr ( cx, expr, recv, & self . msrv ) ,
0 commit comments