summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/tests/ui/repl_uninit.rs
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
commit698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch)
tree173a775858bd501c378080a10dca74132f05bc50 /src/tools/clippy/tests/ui/repl_uninit.rs
parentInitial commit. (diff)
downloadrustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz
rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/tools/clippy/tests/ui/repl_uninit.rs')
-rw-r--r--src/tools/clippy/tests/ui/repl_uninit.rs41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/tools/clippy/tests/ui/repl_uninit.rs b/src/tools/clippy/tests/ui/repl_uninit.rs
new file mode 100644
index 000000000..6c7e2b854
--- /dev/null
+++ b/src/tools/clippy/tests/ui/repl_uninit.rs
@@ -0,0 +1,41 @@
+#![allow(deprecated, invalid_value, clippy::uninit_assumed_init)]
+#![warn(clippy::mem_replace_with_uninit)]
+
+use std::mem;
+
+fn might_panic<X>(x: X) -> X {
+ // in practice this would be a possibly-panicky operation
+ x
+}
+
+fn main() {
+ let mut v = vec![0i32; 4];
+ // the following is UB if `might_panic` panics
+ unsafe {
+ let taken_v = mem::replace(&mut v, mem::uninitialized());
+ let new_v = might_panic(taken_v);
+ std::mem::forget(mem::replace(&mut v, new_v));
+ }
+
+ unsafe {
+ let taken_v = mem::replace(&mut v, mem::MaybeUninit::uninit().assume_init());
+ let new_v = might_panic(taken_v);
+ std::mem::forget(mem::replace(&mut v, new_v));
+ }
+
+ unsafe {
+ let taken_v = mem::replace(&mut v, mem::zeroed());
+ let new_v = might_panic(taken_v);
+ std::mem::forget(mem::replace(&mut v, new_v));
+ }
+
+ // this is silly but OK, because usize is a primitive type
+ let mut u: usize = 42;
+ let uref = &mut u;
+ let taken_u = unsafe { mem::replace(uref, mem::zeroed()) };
+ *uref = taken_u + 1;
+
+ // this is still not OK, because uninit
+ let taken_u = unsafe { mem::replace(uref, mem::uninitialized()) };
+ *uref = taken_u + 1;
+}