Open
Description
Summary
When type implements Copy
trait, especially when its size is small (e.g. an enum without variables), it would make sense to suggest changing signature to pass-by-value.
Lint Name
trivially_copy_pass_by_ref
Reproducer
I tried this code with pedantic clippy:
#[derive(Clone, Copy)]
pub enum Format {
Gif,
Jpeg,
Json,
Mvt,
Png,
Webp,
}
pub fn main() {
let v = Format::Gif;
let _ = v.use_ref();
let _ = v.use_self();
let _ = v.use_ref();
let _ = v.use_self();
}
impl Format {
// This is NOT optimal because of the reference
#[inline(never)]
pub fn use_ref(&self) -> bool {
match *self {
Self::Png | Self::Jpeg | Self::Gif | Self::Webp => true,
Self::Mvt | Self::Json => false,
}
}
// This function should not generate a warning
#[inline(never)]
pub fn use_self(self) -> bool {
match self {
Self::Png | Self::Jpeg | Self::Gif | Self::Webp => true,
Self::Mvt | Self::Json => false,
}
}
}
I expected to see this happen:
A suggestion to use self
instead of &self
Instead, this happened:
no warnings
Assembly
https://rust.godbolt.org/z/xxf6eqcax
example::Format::use_self:
and dil, -2
cmp dil, 2
setne al
ret
example::Format::use_ref:
movzx eax, byte ptr [rdi] # <-- memory access is slower than register access
and al, 6
cmp al, 2
setne al
ret
Version
rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: x86_64-unknown-linux-gnu
release: 1.75.0
LLVM version: 17.0.6