1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
|
#![allow(
clippy::manual_async_fn,
clippy::needless_borrow,
clippy::needless_borrows_for_generic_args,
clippy::needless_lifetimes,
clippy::owned_cow,
clippy::ptr_arg,
clippy::uninlined_format_args
)]
#![warn(clippy::unnecessary_to_owned, clippy::redundant_clone)]
use std::borrow::Cow;
use std::ffi::{CStr, CString, OsStr, OsString};
use std::ops::Deref;
#[derive(Clone)]
struct X(String);
impl Deref for X {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl AsRef<str> for X {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
#[allow(clippy::to_string_trait_impl)]
impl ToString for X {
fn to_string(&self) -> String {
self.0.to_string()
}
}
impl X {
fn join(&self, other: impl AsRef<str>) -> Self {
let mut s = self.0.clone();
s.push_str(other.as_ref());
Self(s)
}
}
#[allow(dead_code)]
#[derive(Clone)]
enum FileType {
Account,
PrivateKey,
Certificate,
}
fn main() {
let c_str = CStr::from_bytes_with_nul(&[0]).unwrap();
let os_str = OsStr::new("x");
let path = std::path::Path::new("x");
let s = "x";
let array = ["x"];
let array_ref = &["x"];
let slice = &["x"][..];
let x = X(String::from("x"));
let x_ref = &x;
require_c_str(&Cow::from(c_str));
//~^ unnecessary_to_owned
require_c_str(c_str);
//~^ unnecessary_to_owned
require_os_str(os_str);
//~^ unnecessary_to_owned
require_os_str(&Cow::from(os_str));
//~^ unnecessary_to_owned
require_os_str(os_str);
//~^ unnecessary_to_owned
require_path(path);
//~^ unnecessary_to_owned
require_path(&Cow::from(path));
//~^ unnecessary_to_owned
require_path(path);
//~^ unnecessary_to_owned
require_str(s);
//~^ unnecessary_to_owned
require_str(&Cow::from(s));
//~^ unnecessary_to_owned
require_str(s);
//~^ unnecessary_to_owned
require_str(x_ref.as_ref());
//~^ unnecessary_to_owned
require_slice(slice);
//~^ unnecessary_to_owned
require_slice(&Cow::from(slice));
//~^ unnecessary_to_owned
require_slice(array.as_ref());
//~^ unnecessary_to_owned
require_slice(array_ref.as_ref());
//~^ unnecessary_to_owned
require_slice(slice);
//~^ unnecessary_to_owned
require_slice(&x_ref.to_owned()); // No longer flagged because of #8759.
require_x(&Cow::<X>::Owned(x.clone()));
//~^ unnecessary_to_owned
require_x(&x_ref.to_owned()); // No longer flagged because of #8759.
require_deref_c_str(c_str);
//~^ unnecessary_to_owned
require_deref_os_str(os_str);
//~^ unnecessary_to_owned
require_deref_path(path);
//~^ unnecessary_to_owned
require_deref_str(s);
//~^ unnecessary_to_owned
require_deref_slice(slice);
//~^ unnecessary_to_owned
require_impl_deref_c_str(c_str);
//~^ unnecessary_to_owned
require_impl_deref_os_str(os_str);
//~^ unnecessary_to_owned
require_impl_deref_path(path);
//~^ unnecessary_to_owned
require_impl_deref_str(s);
//~^ unnecessary_to_owned
require_impl_deref_slice(slice);
//~^ unnecessary_to_owned
require_deref_str_slice(s, slice);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
require_deref_slice_str(slice, s);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
require_as_ref_c_str(c_str);
//~^ unnecessary_to_owned
require_as_ref_os_str(os_str);
//~^ unnecessary_to_owned
require_as_ref_path(path);
//~^ unnecessary_to_owned
require_as_ref_str(s);
//~^ unnecessary_to_owned
require_as_ref_str(&x);
//~^ unnecessary_to_owned
require_as_ref_slice(array);
//~^ unnecessary_to_owned
require_as_ref_slice(array_ref);
//~^ unnecessary_to_owned
require_as_ref_slice(slice);
//~^ unnecessary_to_owned
require_impl_as_ref_c_str(c_str);
//~^ unnecessary_to_owned
require_impl_as_ref_os_str(os_str);
//~^ unnecessary_to_owned
require_impl_as_ref_path(path);
//~^ unnecessary_to_owned
require_impl_as_ref_str(s);
//~^ unnecessary_to_owned
require_impl_as_ref_str(&x);
//~^ unnecessary_to_owned
require_impl_as_ref_slice(array);
//~^ unnecessary_to_owned
require_impl_as_ref_slice(array_ref);
//~^ unnecessary_to_owned
require_impl_as_ref_slice(slice);
//~^ unnecessary_to_owned
require_as_ref_str_slice(s, array);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
require_as_ref_str_slice(s, array_ref);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
require_as_ref_str_slice(s, slice);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
require_as_ref_slice_str(array, s);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
require_as_ref_slice_str(array_ref, s);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
require_as_ref_slice_str(slice, s);
//~^ unnecessary_to_owned
//~| unnecessary_to_owned
let _ = x.join(x_ref);
//~^ unnecessary_to_owned
let _ = slice.iter().copied();
//~^ unnecessary_to_owned
let _ = slice.iter().copied();
//~^ unnecessary_to_owned
let _ = slice.iter().copied();
//~^ unnecessary_to_owned
let _ = slice.iter().copied();
//~^ unnecessary_to_owned
let _ = check_files(&[FileType::Account]);
// negative tests
require_string(&s.to_string());
require_string(&Cow::from(s).into_owned());
require_string(&s.to_owned());
require_string(&x_ref.to_string());
// `X` isn't copy.
require_slice(&x.to_owned());
require_deref_slice(x.to_owned());
// The following should be flagged by `redundant_clone`, but not by this lint.
require_c_str(&CString::from_vec_with_nul(vec![0]).unwrap());
//~^ redundant_clone
require_os_str(&OsString::from("x"));
//~^ redundant_clone
require_path(&std::path::PathBuf::from("x"));
//~^ redundant_clone
require_str(&String::from("x"));
//~^ redundant_clone
require_slice(&[String::from("x")]);
//~^ redundant_clone
let slice = [0u8; 1024];
let _ref_str: &str = core::str::from_utf8(&slice).expect("not UTF-8");
//~^ unnecessary_to_owned
let _ref_str: &str = core::str::from_utf8(b"foo").unwrap();
//~^ unnecessary_to_owned
let _ref_str: &str = core::str::from_utf8(b"foo".as_slice()).unwrap();
//~^ unnecessary_to_owned
// Expression is of type `&String`, can't suggest `str::from_utf8` here
let _ref_string = &String::from_utf8(b"foo".to_vec()).unwrap();
macro_rules! arg_from_macro {
() => {
b"foo".to_vec()
};
}
macro_rules! string_from_utf8_from_macro {
() => {
&String::from_utf8(b"foo".to_vec()).unwrap()
};
}
let _ref_str: &str = &String::from_utf8(arg_from_macro!()).unwrap();
let _ref_str: &str = string_from_utf8_from_macro!();
}
fn require_c_str(_: &CStr) {}
fn require_os_str(_: &OsStr) {}
fn require_path(_: &std::path::Path) {}
fn require_str(_: &str) {}
fn require_slice<T>(_: &[T]) {}
fn require_x(_: &X) {}
fn require_deref_c_str<T: Deref<Target = CStr>>(_: T) {}
fn require_deref_os_str<T: Deref<Target = OsStr>>(_: T) {}
fn require_deref_path<T: Deref<Target = std::path::Path>>(_: T) {}
fn require_deref_str<T: Deref<Target = str>>(_: T) {}
fn require_deref_slice<T, U: Deref<Target = [T]>>(_: U) {}
fn require_impl_deref_c_str(_: impl Deref<Target = CStr>) {}
fn require_impl_deref_os_str(_: impl Deref<Target = OsStr>) {}
fn require_impl_deref_path(_: impl Deref<Target = std::path::Path>) {}
fn require_impl_deref_str(_: impl Deref<Target = str>) {}
fn require_impl_deref_slice<T>(_: impl Deref<Target = [T]>) {}
fn require_deref_str_slice<T: Deref<Target = str>, U, V: Deref<Target = [U]>>(_: T, _: V) {}
fn require_deref_slice_str<T, U: Deref<Target = [T]>, V: Deref<Target = str>>(_: U, _: V) {}
fn require_as_ref_c_str<T: AsRef<CStr>>(_: T) {}
fn require_as_ref_os_str<T: AsRef<OsStr>>(_: T) {}
fn require_as_ref_path<T: AsRef<std::path::Path>>(_: T) {}
fn require_as_ref_str<T: AsRef<str>>(_: T) {}
fn require_as_ref_slice<T, U: AsRef<[T]>>(_: U) {}
fn require_impl_as_ref_c_str(_: impl AsRef<CStr>) {}
fn require_impl_as_ref_os_str(_: impl AsRef<OsStr>) {}
fn require_impl_as_ref_path(_: impl AsRef<std::path::Path>) {}
fn require_impl_as_ref_str(_: impl AsRef<str>) {}
fn require_impl_as_ref_slice<T>(_: impl AsRef<[T]>) {}
fn require_as_ref_str_slice<T: AsRef<str>, U, V: AsRef<[U]>>(_: T, _: V) {}
fn require_as_ref_slice_str<T, U: AsRef<[T]>, V: AsRef<str>>(_: U, _: V) {}
// `check_files` is based on:
// https://github.com/breard-r/acmed/blob/1f0dcc32aadbc5e52de6d23b9703554c0f925113/acmed/src/storage.rs#L262
fn check_files(file_types: &[FileType]) -> bool {
for t in file_types {
//~^ unnecessary_to_owned
let path = match get_file_path(t) {
Ok(p) => p,
Err(_) => {
return false;
},
};
if !path.is_file() {
return false;
}
}
true
}
fn get_file_path(_file_type: &FileType) -> Result<std::path::PathBuf, std::io::Error> {
Ok(std::path::PathBuf::new())
}
fn require_string(_: &String) {}
// https://github.com/rust-lang/rust-clippy/issues/8507
mod issue_8507 {
#![allow(dead_code)]
struct Opaque<P>(P);
pub trait Abstracted {}
impl<P> Abstracted for Opaque<P> {}
fn build<P>(p: P) -> Opaque<P>
where
P: AsRef<str>,
{
Opaque(p)
}
// Should not lint.
fn test_str(s: &str) -> Box<dyn Abstracted> {
Box::new(build(s.to_string()))
}
// Should not lint.
fn test_x(x: super::X) -> Box<dyn Abstracted> {
Box::new(build(x))
}
#[derive(Clone, Copy)]
struct Y(&'static str);
impl AsRef<str> for Y {
fn as_ref(&self) -> &str {
self.0
}
}
#[allow(clippy::to_string_trait_impl)]
impl ToString for Y {
fn to_string(&self) -> String {
self.0.to_string()
}
}
// Should lint because Y is copy.
fn test_y(y: Y) -> Box<dyn Abstracted> {
Box::new(build(y))
//~^ unnecessary_to_owned
}
}
// https://github.com/rust-lang/rust-clippy/issues/8759
mod issue_8759 {
#![allow(dead_code)]
#[derive(Default)]
struct View {}
impl std::borrow::ToOwned for View {
type Owned = View;
fn to_owned(&self) -> Self::Owned {
View {}
}
}
#[derive(Default)]
struct RenderWindow {
default_view: View,
}
impl RenderWindow {
fn default_view(&self) -> &View {
&self.default_view
}
fn set_view(&mut self, _view: &View) {}
}
fn main() {
let mut rw = RenderWindow::default();
rw.set_view(&rw.default_view().to_owned());
}
}
mod issue_8759_variant {
#![allow(dead_code)]
#[derive(Clone, Default)]
struct View {}
#[derive(Default)]
struct RenderWindow {
default_view: View,
}
impl RenderWindow {
fn default_view(&self) -> &View {
&self.default_view
}
fn set_view(&mut self, _view: &View) {}
}
fn main() {
let mut rw = RenderWindow::default();
rw.set_view(&rw.default_view().to_owned());
}
}
mod issue_9317 {
#![allow(dead_code)]
struct Bytes {}
#[allow(clippy::to_string_trait_impl)]
impl ToString for Bytes {
fn to_string(&self) -> String {
"123".to_string()
}
}
impl AsRef<[u8]> for Bytes {
fn as_ref(&self) -> &[u8] {
&[1, 2, 3]
}
}
fn consume<C: AsRef<[u8]>>(c: C) {
let _ = c;
}
pub fn main() {
let b = Bytes {};
// Should not lint.
consume(b.to_string());
}
}
mod issue_9351 {
#![allow(dead_code)]
use std::ops::Deref;
use std::path::{Path, PathBuf};
fn require_deref_path<T: Deref<Target = std::path::Path>>(x: T) -> T {
x
}
fn generic_arg_used_elsewhere<T: AsRef<Path>>(_x: T, _y: T) {}
fn id<T: AsRef<str>>(x: T) -> T {
x
}
fn predicates_are_satisfied(_x: impl std::fmt::Write) {}
// Should lint
fn single_return() -> impl AsRef<str> {
id("abc")
//~^ unnecessary_to_owned
}
// Should not lint
fn multiple_returns(b: bool) -> impl AsRef<str> {
if b {
return String::new();
}
id("abc".to_string())
}
struct S1(String);
// Should not lint
fn fields1() -> S1 {
S1(id("abc".to_string()))
}
struct S2 {
s: String,
}
// Should not lint
fn fields2() {
let mut s = S2 { s: "abc".into() };
s.s = id("abc".to_string());
}
pub fn main() {
let path = std::path::Path::new("x");
let path_buf = path.to_owned();
// Should not lint.
let _x: PathBuf = require_deref_path(path.to_owned());
generic_arg_used_elsewhere(path.to_owned(), path_buf);
predicates_are_satisfied(id("abc".to_string()));
}
}
mod issue_9504 {
#![allow(dead_code)]
async fn foo<S: AsRef<str>>(_: S) {}
async fn bar() {
foo(std::path::PathBuf::new().to_string_lossy().to_string()).await;
}
}
mod issue_9771a {
#![allow(dead_code)]
use std::marker::PhantomData;
pub struct Key<K: AsRef<[u8]>, V: ?Sized>(K, PhantomData<V>);
impl<K: AsRef<[u8]>, V: ?Sized> Key<K, V> {
pub fn new(key: K) -> Key<K, V> {
Key(key, PhantomData)
}
}
pub fn pkh(pkh: &[u8]) -> Key<Vec<u8>, String> {
Key::new([b"pkh-", pkh].concat().to_vec())
}
}
mod issue_9771b {
#![allow(dead_code)]
pub struct Key<K: AsRef<[u8]>>(K);
pub fn from(c: &[u8]) -> Key<Vec<u8>> {
let v = [c].concat();
Key(v.to_vec())
}
}
// This is a watered down version of the code in: https://github.com/oxigraph/rio
// The ICE is triggered by the call to `to_owned` on this line:
// https://github.com/oxigraph/rio/blob/66635b9ff8e5423e58932353fa40d6e64e4820f7/testsuite/src/parser_evaluator.rs#L116
mod issue_10021 {
#![allow(unused)]
pub struct Iri<T>(T);
impl<T: AsRef<str>> Iri<T> {
pub fn parse(iri: T) -> Result<Self, ()> {
unimplemented!()
}
}
pub fn parse_w3c_rdf_test_file(url: &str) -> Result<(), ()> {
let base_iri = Iri::parse(url.to_owned())?;
Ok(())
}
}
mod issue_10033 {
#![allow(dead_code)]
use std::fmt::Display;
use std::ops::Deref;
fn _main() {
let f = Foo;
// Not actually unnecessary - this calls `Foo`'s `Display` impl, not `str`'s (even though `Foo` does
// deref to `str`)
foo(&f.to_string());
}
fn foo(s: &str) {
println!("{}", s);
}
struct Foo;
impl Deref for Foo {
type Target = str;
fn deref(&self) -> &Self::Target {
"str"
}
}
impl Display for Foo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Foo")
}
}
}
mod issue_11952 {
use core::future::{Future, IntoFuture};
fn foo<'a, T: AsRef<[u8]>>(x: T, y: &'a i32) -> impl 'a + Future<Output = Result<(), ()>> {
async move {
let _y = y;
Ok(())
}
}
fn bar() {
IntoFuture::into_future(foo([], &0));
//~^ unnecessary_to_owned
}
}
fn borrow_checks() {
use std::borrow::Borrow;
use std::collections::HashSet;
fn inner(a: &[&str]) {
let mut s = HashSet::from([vec!["a"]]);
s.remove(a);
//~^ unnecessary_to_owned
}
let mut s = HashSet::from(["a".to_string()]);
s.remove("b");
//~^ unnecessary_to_owned
s.remove("b");
//~^ unnecessary_to_owned
// Should not warn.
s.remove("b");
let mut s = HashSet::from([vec!["a"]]);
s.remove(["b"].as_slice());
//~^ unnecessary_to_owned
s.remove((&["b"]).as_slice());
//~^ unnecessary_to_owned
// Should not warn.
s.remove(&["b"].to_vec().clone());
s.remove(["a"].as_slice());
trait SetExt {
fn foo<Q: Borrow<str>>(&self, _: &String);
}
impl<K> SetExt for HashSet<K> {
fn foo<Q: Borrow<str>>(&self, _: &String) {}
}
// Should not lint!
HashSet::<i32>::new().foo::<&str>(&"".to_owned());
HashSet::<String>::new().get(&1.to_string());
}
fn issue13624() -> impl IntoIterator {
let cow: Cow<'_, Vec<String>> = Cow::Owned(vec![String::from("foo")]);
cow.into_owned().into_iter()
}
mod issue_14242 {
use std::rc::Rc;
#[derive(Copy, Clone)]
struct Foo;
fn rc_slice_provider() -> Rc<[Foo]> {
Rc::from([Foo])
}
fn iterator_provider() -> impl Iterator<Item = Foo> {
rc_slice_provider().to_vec().into_iter()
}
}
fn issue14833() {
use std::collections::HashSet;
let mut s = HashSet::<&String>::new();
s.remove(&"hello".to_owned());
}
|