2018-04-11 09:17:59 +00:00
|
|
|
//! Test casts for alignment issues
|
|
|
|
|
2018-12-12 16:17:01 +00:00
|
|
|
#![feature(rustc_private)]
|
2022-04-07 17:39:59 +00:00
|
|
|
#![feature(core_intrinsics)]
|
2018-04-18 00:13:19 +00:00
|
|
|
extern crate libc;
|
|
|
|
|
2018-07-28 15:34:52 +00:00
|
|
|
#[warn(clippy::cast_ptr_alignment)]
|
2022-01-13 12:18:19 +00:00
|
|
|
#[allow(
|
|
|
|
clippy::no_effect,
|
|
|
|
clippy::unnecessary_operation,
|
|
|
|
clippy::cast_lossless,
|
|
|
|
clippy::borrow_as_ptr
|
|
|
|
)]
|
|
|
|
|
2018-04-11 09:17:59 +00:00
|
|
|
fn main() {
|
|
|
|
/* These should be warned against */
|
|
|
|
|
|
|
|
// cast to more-strictly-aligned type
|
|
|
|
(&1u8 as *const u8) as *const u16;
|
2023-08-24 19:32:12 +00:00
|
|
|
//~^ ERROR: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`)
|
|
|
|
//~| NOTE: `-D clippy::cast-ptr-alignment` implied by `-D warnings`
|
2018-04-11 09:17:59 +00:00
|
|
|
(&mut 1u8 as *mut u8) as *mut u16;
|
2023-08-24 19:32:12 +00:00
|
|
|
//~^ ERROR: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1
|
2018-04-11 09:17:59 +00:00
|
|
|
|
2021-01-15 09:56:44 +00:00
|
|
|
// cast to more-strictly-aligned type, but with the `pointer::cast` function.
|
|
|
|
(&1u8 as *const u8).cast::<u16>();
|
2023-08-24 19:32:12 +00:00
|
|
|
//~^ ERROR: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`)
|
2021-01-15 09:56:44 +00:00
|
|
|
(&mut 1u8 as *mut u8).cast::<u16>();
|
2023-08-24 19:32:12 +00:00
|
|
|
//~^ ERROR: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1
|
2021-01-15 09:56:44 +00:00
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
/* These should be ok */
|
2018-04-11 09:17:59 +00:00
|
|
|
|
|
|
|
// not a pointer type
|
|
|
|
1u8 as u16;
|
|
|
|
// cast to less-strictly-aligned type
|
|
|
|
(&1u16 as *const u16) as *const u8;
|
|
|
|
(&mut 1u16 as *mut u16) as *mut u8;
|
2018-04-18 00:13:19 +00:00
|
|
|
// For c_void, we should trust the user. See #2677
|
|
|
|
(&1u32 as *const u32 as *const std::os::raw::c_void) as *const u32;
|
|
|
|
(&1u32 as *const u32 as *const libc::c_void) as *const u32;
|
2019-07-06 09:40:14 +00:00
|
|
|
// For ZST, we should trust the user. See #4256
|
|
|
|
(&1u32 as *const u32 as *const ()) as *const u32;
|
2022-04-07 17:39:59 +00:00
|
|
|
|
|
|
|
// Issue #2881
|
|
|
|
let mut data = [0u8, 0u8];
|
|
|
|
unsafe {
|
|
|
|
let ptr = &data as *const [u8; 2] as *const u8;
|
|
|
|
let _ = (ptr as *const u16).read_unaligned();
|
|
|
|
let _ = core::ptr::read_unaligned(ptr as *const u16);
|
|
|
|
let _ = core::intrinsics::unaligned_volatile_load(ptr as *const u16);
|
|
|
|
let ptr = &mut data as *mut [u8; 2] as *mut u8;
|
2022-05-05 14:12:52 +00:00
|
|
|
(ptr as *mut u16).write_unaligned(0);
|
|
|
|
core::ptr::write_unaligned(ptr as *mut u16, 0);
|
|
|
|
core::intrinsics::unaligned_volatile_store(ptr as *mut u16, 0);
|
2022-04-07 17:39:59 +00:00
|
|
|
}
|
2018-04-11 09:17:59 +00:00
|
|
|
}
|