@@ -71,6 +71,7 @@ mod no_effect_replace;
71
71
mod obfuscated_if_else;
72
72
mod ok_expect;
73
73
mod open_options;
74
+ mod option_as_ref_cloned;
74
75
mod option_as_ref_deref;
75
76
mod option_map_or_err_ok;
76
77
mod option_map_or_none;
@@ -3887,6 +3888,31 @@ declare_clippy_lint! {
3887
3888
"splitting a trimmed string at hard-coded newlines"
3888
3889
}
3889
3890
3891
+ declare_clippy_lint ! {
3892
+ /// ### What it does
3893
+ /// Checks for usage of `.as_ref().cloned()` and `.as_mut().cloned()` on `Option`s
3894
+ ///
3895
+ /// ### Why is this bad?
3896
+ /// This can be written more concisely by cloning the `Option` directly.
3897
+ ///
3898
+ /// ### Example
3899
+ /// ```no_run
3900
+ /// fn foo(bar: &Option<Vec<u8>>) -> Option<Vec<u8>> {
3901
+ /// bar.as_ref().cloned()
3902
+ /// }
3903
+ /// ```
3904
+ /// Use instead:
3905
+ /// ```no_run
3906
+ /// fn foo(bar: &Option<Vec<u8>>) -> Option<Vec<u8>> {
3907
+ /// bar.clone()
3908
+ /// }
3909
+ /// ```
3910
+ #[ clippy:: version = "1.77.0" ]
3911
+ pub OPTION_AS_REF_CLONED ,
3912
+ pedantic,
3913
+ "cloning an `Option` via `as_ref().cloned()`"
3914
+ }
3915
+
3890
3916
pub struct Methods {
3891
3917
avoid_breaking_exported_api : bool ,
3892
3918
msrv : Msrv ,
@@ -4043,6 +4069,7 @@ impl_lint_pass!(Methods => [
4043
4069
ITER_FILTER_IS_OK ,
4044
4070
MANUAL_IS_VARIANT_AND ,
4045
4071
STR_SPLIT_AT_NEWLINE ,
4072
+ OPTION_AS_REF_CLONED ,
4046
4073
] ) ;
4047
4074
4048
4075
/// Extracts a method call name, args, and `Span` of the method name.
@@ -4290,7 +4317,10 @@ impl Methods {
4290
4317
( "as_mut" , [ ] ) => useless_asref:: check ( cx, expr, "as_mut" , recv) ,
4291
4318
( "as_ref" , [ ] ) => useless_asref:: check ( cx, expr, "as_ref" , recv) ,
4292
4319
( "assume_init" , [ ] ) => uninit_assumed_init:: check ( cx, expr, recv) ,
4293
- ( "cloned" , [ ] ) => cloned_instead_of_copied:: check ( cx, expr, recv, span, & self . msrv ) ,
4320
+ ( "cloned" , [ ] ) => {
4321
+ cloned_instead_of_copied:: check ( cx, expr, recv, span, & self . msrv ) ;
4322
+ option_as_ref_cloned:: check ( cx, recv, span) ;
4323
+ } ,
4294
4324
( "collect" , [ ] ) if is_trait_method ( cx, expr, sym:: Iterator ) => {
4295
4325
needless_collect:: check ( cx, span, expr, recv, call_span) ;
4296
4326
match method_call ( recv) {
0 commit comments