rust/tests/ui/suspicious_to_owned.rs
Marco Mastropaolo de028e2fb9 Implemented suspicious_to_owned lint to check if to_owned is called on a Cow.
This is done because `to_owned` is very similarly named to `into_owned`, but the
effect of calling those two methods is completely different. This creates
confusion (stemming from the ambiguity of the 'owned' term in the context of
`Cow`s) and might not be what the writer intended.
2022-08-26 17:41:17 -07:00

63 lines
1.8 KiB
Rust

#![warn(clippy::suspicious_to_owned)]
#![warn(clippy::implicit_clone)]
#![allow(clippy::redundant_clone)]
use std::borrow::Cow;
use std::ffi::CStr;
fn main() {
let moo = "Moooo";
let c_moo = b"Moooo\0";
let c_moo_ptr = c_moo.as_ptr() as *const i8;
let moos = ['M', 'o', 'o'];
let moos_vec = moos.to_vec();
// we expect this to be linted
let cow = Cow::Borrowed(moo);
let _ = cow.to_owned();
// we expect no lints for this
let cow = Cow::Borrowed(moo);
let _ = cow.into_owned();
// we expect no lints for this
let cow = Cow::Borrowed(moo);
let _ = cow.clone();
// we expect this to be linted
let cow = Cow::Borrowed(&moos);
let _ = cow.to_owned();
// we expect no lints for this
let cow = Cow::Borrowed(&moos);
let _ = cow.into_owned();
// we expect no lints for this
let cow = Cow::Borrowed(&moos);
let _ = cow.clone();
// we expect this to be linted
let cow = Cow::Borrowed(&moos_vec);
let _ = cow.to_owned();
// we expect no lints for this
let cow = Cow::Borrowed(&moos_vec);
let _ = cow.into_owned();
// we expect no lints for this
let cow = Cow::Borrowed(&moos_vec);
let _ = cow.clone();
// we expect this to be linted
let cow = unsafe { CStr::from_ptr(c_moo_ptr) }.to_string_lossy();
let _ = cow.to_owned();
// we expect no lints for this
let cow = unsafe { CStr::from_ptr(c_moo_ptr) }.to_string_lossy();
let _ = cow.into_owned();
// we expect no lints for this
let cow = unsafe { CStr::from_ptr(c_moo_ptr) }.to_string_lossy();
let _ = cow.clone();
// we expect no lints for these
let _ = moo.to_owned();
let _ = c_moo.to_owned();
let _ = moos.to_owned();
// we expect implicit_clone lints for these
let _ = String::from(moo).to_owned();
let _ = moos_vec.to_owned();
}