Skip to content

Commit

Permalink
Rollup merge of #104363 - WaffleLapkin:bonk_box_new, r=Nilstrieb
Browse files Browse the repository at this point in the history
Make `unused_allocation` lint against `Box::new` too

Previously it only linted against `box` syntax, which likely won't ever be stabilized, which is pretty useless. Even now I'm not sure if it's a meaningful lint, but it's at least something 🤷

This means that code like the following will be linted against:
```rust
Box::new([1, 2, 3]).len();
f(&Box::new(1)); // where f : &i32 -> ()
```
The lint works by checking if a `Box::new` (or `box`) expression has an a borrow adjustment, meaning that the code that first stores the box in a variable won't be linted against:
```rust
let boxed = Box::new([1, 2, 3]); // no lint
boxed.len();
```
  • Loading branch information
matthiaskrgr authored Mar 11, 2023
2 parents 1ec010b + 24cd510 commit 4d3e3b6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 16 deletions.
1 change: 1 addition & 0 deletions alloc/src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ impl<T> Box<T> {
#[inline(always)]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[rustc_diagnostic_item = "box_new"]
pub fn new(x: T) -> Self {
#[rustc_box]
Box::new(x)
Expand Down
24 changes: 8 additions & 16 deletions alloc/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use core::any::Any;
use core::clone::Clone;
use core::convert::TryInto;
use core::ops::Deref;
use core::result::Result::{Err, Ok};

use std::boxed::Box;

Expand All @@ -15,32 +14,25 @@ fn test_owned_clone() {
assert!(a == b);
}

#[derive(PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq)]
struct Test;

#[test]
fn any_move() {
let a = Box::new(8) as Box<dyn Any>;
let b = Box::new(Test) as Box<dyn Any>;

match a.downcast::<i32>() {
Ok(a) => {
assert!(a == Box::new(8));
}
Err(..) => panic!(),
}
match b.downcast::<Test>() {
Ok(a) => {
assert!(a == Box::new(Test));
}
Err(..) => panic!(),
}
let a: Box<i32> = a.downcast::<i32>().unwrap();
assert_eq!(*a, 8);

let b: Box<Test> = b.downcast::<Test>().unwrap();
assert_eq!(*b, Test);

let a = Box::new(8) as Box<dyn Any>;
let b = Box::new(Test) as Box<dyn Any>;

assert!(a.downcast::<Box<Test>>().is_err());
assert!(b.downcast::<Box<i32>>().is_err());
assert!(a.downcast::<Box<i32>>().is_err());
assert!(b.downcast::<Box<Test>>().is_err());
}

#[test]
Expand Down

0 comments on commit 4d3e3b6

Please sign in to comment.