refactor: warn on and satisfy clippy::{ptr_as_ptr,ref_as_ptr} in wgpu-{core,hal,types}

…using `cargo +1.79.0 clippy --workspace --all-features --all-targets
--fix`, plus some manual changes to (1) catch some missed cases (not run
on all platforms?) and (2) `--fix` doesn't make things compile again. 😀
This commit is contained in:
Erich Gubler 2024-07-24 10:10:29 -04:00
parent 06649a39f3
commit 723995d9a9
21 changed files with 66 additions and 63 deletions

View File

@ -1170,7 +1170,7 @@ impl Global {
#[cfg(feature = "trace")]
if let Some(ref mut trace) = *device.trace.lock() {
let data = trace.make_binary("spv", unsafe {
std::slice::from_raw_parts(source.as_ptr() as *const u8, source.len() * 4)
std::slice::from_raw_parts(source.as_ptr().cast::<u8>(), source.len() * 4)
});
trace.add(trace::Action::CreateShaderModule {
id: fid.id(),

View File

@ -642,7 +642,7 @@ impl Global {
) -> Result<SurfaceId, CreateSurfaceError> {
profiling::scope!("Instance::instance_create_surface_from_visual");
self.instance_create_surface_dx12(id_in, |inst| unsafe {
inst.create_surface_from_visual(visual as _)
inst.create_surface_from_visual(visual.cast())
})
}
@ -672,7 +672,7 @@ impl Global {
) -> Result<SurfaceId, CreateSurfaceError> {
profiling::scope!("Instance::instance_create_surface_from_swap_chain_panel");
self.instance_create_surface_dx12(id_in, |inst| unsafe {
inst.create_surface_from_swap_chain_panel(swap_chain_panel as _)
inst.create_surface_from_swap_chain_panel(swap_chain_panel.cast())
})
}

View File

@ -55,6 +55,7 @@ the documentation for `wgpu-core` is empty unless built with
rustdoc::private_intra_doc_links
)]
#![warn(
clippy::ptr_as_ptr,
trivial_casts,
trivial_numeric_casts,
unsafe_op_in_unsafe_fn,

View File

@ -83,7 +83,7 @@ impl RenderDoc {
match unsafe { get_api(10401, &mut obj) } {
1 => RenderDoc::Available {
api: RenderDocApi {
api: unsafe { *(obj as *mut renderdoc_sys::RENDERDOC_API_1_4_1) },
api: unsafe { *obj.cast::<renderdoc_sys::RENDERDOC_API_1_4_1>() },
lib: renderdoc_lib,
},
},

View File

@ -88,7 +88,7 @@ impl super::Adapter {
unsafe {
device.CheckFeatureSupport(
d3d12_ty::D3D12_FEATURE_FEATURE_LEVELS,
&mut device_levels as *mut _ as *mut _,
ptr::from_mut(&mut device_levels).cast(),
mem::size_of::<d3d12_ty::D3D12_FEATURE_DATA_FEATURE_LEVELS>() as _,
)
};
@ -111,7 +111,7 @@ impl super::Adapter {
assert_eq!(0, unsafe {
device.CheckFeatureSupport(
d3d12_ty::D3D12_FEATURE_ARCHITECTURE,
&mut features_architecture as *mut _ as *mut _,
ptr::from_mut(&mut features_architecture).cast(),
mem::size_of::<d3d12_ty::D3D12_FEATURE_DATA_ARCHITECTURE>() as _,
)
});
@ -156,7 +156,7 @@ impl super::Adapter {
assert_eq!(0, unsafe {
device.CheckFeatureSupport(
d3d12_ty::D3D12_FEATURE_D3D12_OPTIONS,
&mut options as *mut _ as *mut _,
ptr::from_mut(&mut options).cast(),
mem::size_of::<d3d12_ty::D3D12_FEATURE_DATA_D3D12_OPTIONS>() as _,
)
});
@ -167,7 +167,7 @@ impl super::Adapter {
let hr = unsafe {
device.CheckFeatureSupport(
d3d12_ty::D3D12_FEATURE_D3D12_OPTIONS2,
&mut features2 as *mut _ as *mut _,
ptr::from_mut(&mut features2).cast(),
mem::size_of::<d3d12_ty::D3D12_FEATURE_DATA_D3D12_OPTIONS2>() as _,
)
};
@ -180,7 +180,7 @@ impl super::Adapter {
let hr = unsafe {
device.CheckFeatureSupport(
21, // D3D12_FEATURE_D3D12_OPTIONS3
&mut features3 as *mut _ as *mut _,
ptr::from_mut(&mut features3).cast(),
mem::size_of::<crate::dx12::types::D3D12_FEATURE_DATA_D3D12_OPTIONS3>() as _,
)
};
@ -210,7 +210,7 @@ impl super::Adapter {
if 0 == unsafe {
device.CheckFeatureSupport(
7, // D3D12_FEATURE_SHADER_MODEL
&mut sm as *mut _ as *mut _,
ptr::from_mut(&mut sm).cast(),
mem::size_of::<crate::dx12::types::D3D12_FEATURE_DATA_SHADER_MODEL>()
as _,
)
@ -337,7 +337,7 @@ impl super::Adapter {
let hr = unsafe {
device.CheckFeatureSupport(
d3d12_ty::D3D12_FEATURE_FORMAT_SUPPORT,
&mut bgra8unorm_info as *mut _ as *mut _,
ptr::from_mut(&mut bgra8unorm_info).cast(),
mem::size_of::<d3d12_ty::D3D12_FEATURE_DATA_FORMAT_SUPPORT>() as _,
)
};
@ -353,7 +353,7 @@ impl super::Adapter {
let hr = unsafe {
device.CheckFeatureSupport(
d3d12_ty::D3D12_FEATURE_D3D12_OPTIONS1,
&mut features1 as *mut _ as *mut _,
ptr::from_mut(&mut features1).cast(),
mem::size_of::<d3d12_ty::D3D12_FEATURE_DATA_D3D12_OPTIONS1>() as _,
)
};
@ -378,7 +378,7 @@ impl super::Adapter {
let hr = unsafe {
device.CheckFeatureSupport(
37, // D3D12_FEATURE_D3D12_OPTIONS9
&mut features9 as *mut _ as *mut _,
ptr::from_mut(&mut features9).cast(),
mem::size_of::<crate::dx12::types::D3D12_FEATURE_DATA_D3D12_OPTIONS9>() as _,
)
};
@ -586,7 +586,7 @@ impl crate::Adapter for super::Adapter {
assert_eq!(winerror::S_OK, unsafe {
self.device.CheckFeatureSupport(
d3d12_ty::D3D12_FEATURE_FORMAT_SUPPORT,
&mut data as *mut _ as *mut _,
ptr::from_mut(&mut data).cast(),
mem::size_of::<d3d12_ty::D3D12_FEATURE_DATA_FORMAT_SUPPORT>() as _,
)
});

View File

@ -69,7 +69,7 @@ impl super::CommandEncoder {
self.pass.kind = kind;
if let Some(label) = label {
let (wide_label, size) = self.temp.prepare_marker(label);
unsafe { list.BeginEvent(0, wide_label.as_ptr() as *const _, size) };
unsafe { list.BeginEvent(0, wide_label.as_ptr().cast(), size) };
self.pass.has_label = true;
}
self.pass.dirty_root_elements = 0;
@ -950,7 +950,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
self.list
.as_ref()
.unwrap()
.SetMarker(0, wide_label.as_ptr() as *const _, size)
.SetMarker(0, wide_label.as_ptr().cast(), size)
};
}
unsafe fn begin_debug_marker(&mut self, group_label: &str) {
@ -959,7 +959,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
self.list
.as_ref()
.unwrap()
.BeginEvent(0, wide_label.as_ptr() as *const _, size)
.BeginEvent(0, wide_label.as_ptr().cast(), size)
};
}
unsafe fn end_debug_marker(&mut self) {

View File

@ -1386,7 +1386,7 @@ impl crate::Device for super::Device {
};
for attribute in vbuf.attributes {
input_element_descs.push(d3d12_ty::D3D12_INPUT_ELEMENT_DESC {
SemanticName: NAGA_LOCATION_SEMANTIC.as_ptr() as *const _,
SemanticName: NAGA_LOCATION_SEMANTIC.as_ptr().cast(),
SemanticIndex: attribute.shader_location,
Format: auxil::dxgi::conv::map_vertex_format(attribute.format),
InputSlot: i as u32,
@ -1749,7 +1749,7 @@ impl crate::Device for super::Device {
{
unsafe {
self.render_doc
.start_frame_capture(self.raw.as_mut_ptr() as *mut _, ptr::null_mut())
.start_frame_capture(self.raw.as_mut_ptr().cast(), ptr::null_mut())
}
}
#[cfg(not(feature = "renderdoc"))]
@ -1760,7 +1760,7 @@ impl crate::Device for super::Device {
#[cfg(feature = "renderdoc")]
unsafe {
self.render_doc
.end_frame_capture(self.raw.as_mut_ptr() as *mut _, ptr::null_mut())
.end_frame_capture(self.raw.as_mut_ptr().cast(), ptr::null_mut())
}
}

View File

@ -81,7 +81,7 @@ impl crate::Instance for super::Instance {
let hr = unsafe {
factory5.CheckFeatureSupport(
dxgi1_5::DXGI_FEATURE_PRESENT_ALLOW_TEARING,
&mut allow_tearing as *mut _ as *mut _,
std::ptr::from_mut(&mut allow_tearing).cast(),
mem::size_of::<minwindef::BOOL>() as _,
)
};

View File

@ -720,7 +720,7 @@ impl crate::Surface for Surface {
self.factory
.unwrap_factory2()
.create_swapchain_for_composition(
device.present_queue.as_mut_ptr() as *mut _,
device.present_queue.as_mut_ptr().cast(),
&desc,
)
.into_result()
@ -733,7 +733,7 @@ impl crate::Surface for Surface {
.clone()
.ok_or(crate::SurfaceError::Other("IDXGIFactoryMedia not found"))?
.create_swapchain_for_composition_surface_handle(
device.present_queue.as_mut_ptr() as *mut _,
device.present_queue.as_mut_ptr().cast(),
handle,
&desc,
)
@ -745,7 +745,7 @@ impl crate::Surface for Surface {
.as_factory2()
.unwrap()
.create_swapchain_for_hwnd(
device.present_queue.as_mut_ptr() as *mut _,
device.present_queue.as_mut_ptr().cast(),
hwnd,
&desc,
)

View File

@ -81,9 +81,8 @@ impl super::CommandBuffer {
}
fn add_push_constant_data(&mut self, data: &[u32]) -> Range<u32> {
let data_raw = unsafe {
std::slice::from_raw_parts(data.as_ptr() as *const _, mem::size_of_val(data))
};
let data_raw =
unsafe { std::slice::from_raw_parts(data.as_ptr().cast(), mem::size_of_val(data)) };
let start = self.data_bytes.len();
assert!(start < u32::MAX as usize);
self.data_bytes.extend_from_slice(data_raw);

View File

@ -919,7 +919,10 @@ impl crate::Instance for Instance {
let ret = unsafe {
ndk_sys::ANativeWindow_setBuffersGeometry(
handle.a_native_window.as_ptr() as *mut ndk_sys::ANativeWindow,
handle
.a_native_window
.as_ptr()
.cast::<ndk_sys::ANativeWindow>(),
0,
0,
format,
@ -1229,12 +1232,12 @@ impl crate::Surface for Surface {
let native_window_ptr = match (self.wsi.kind, self.raw_window_handle) {
(WindowKind::Unknown | WindowKind::X11, Rwh::Xlib(handle)) => {
temp_xlib_handle = handle.window;
&mut temp_xlib_handle as *mut _ as *mut ffi::c_void
ptr::from_mut(&mut temp_xlib_handle).cast::<ffi::c_void>()
}
(WindowKind::AngleX11, Rwh::Xlib(handle)) => handle.window as *mut ffi::c_void,
(WindowKind::Unknown | WindowKind::X11, Rwh::Xcb(handle)) => {
temp_xcb_handle = handle.window;
&mut temp_xcb_handle as *mut _ as *mut ffi::c_void
ptr::from_mut(&mut temp_xcb_handle).cast::<ffi::c_void>()
}
(WindowKind::AngleX11, Rwh::Xcb(handle)) => {
handle.window.get() as *mut ffi::c_void
@ -1248,7 +1251,7 @@ impl crate::Surface for Surface {
unsafe { library.get(b"wl_egl_window_create") }.unwrap();
let window =
unsafe { wl_egl_window_create(handle.surface.as_ptr(), 640, 480) }
as *mut _;
.cast();
wl_window = Some(window);
window
}
@ -1265,8 +1268,8 @@ impl crate::Surface for Surface {
use objc::{msg_send, runtime::Object, sel, sel_impl};
// ns_view always have a layer and don't need to verify that it exists.
let layer: *mut Object =
msg_send![handle.ns_view.as_ptr() as *mut Object, layer];
layer as *mut ffi::c_void
msg_send![handle.ns_view.as_ptr().cast::<Object>(), layer];
layer.cast::<ffi::c_void>()
};
window_ptr
}

View File

@ -20,7 +20,7 @@ pub unsafe fn enable_extension(extension_name_null_terminated: &str) -> bool {
unsafe {
emscripten_webgl_enable_extension(
emscripten_webgl_get_current_context(),
extension_name_null_terminated.as_ptr() as _,
extension_name_null_terminated.as_ptr().cast(),
) == 1
}
}

View File

@ -955,7 +955,7 @@ impl super::Queue {
}
let query_data = unsafe {
slice::from_raw_parts(
temp_query_results.as_ptr() as *const u8,
temp_query_results.as_ptr().cast::<u8>(),
temp_query_results.len() * mem::size_of::<u64>(),
)
};
@ -1526,8 +1526,7 @@ impl super::Queue {
debug_assert_eq!(data_required, raw.len());
let slice: &[T] =
unsafe { slice::from_raw_parts(raw.as_ptr() as *const _, COUNT) };
let slice: &[T] = unsafe { slice::from_raw_parts(raw.as_ptr().cast(), COUNT) };
slice.try_into().unwrap()
}

View File

@ -59,7 +59,7 @@ impl AdapterContext {
}
pub fn raw_context(&self) -> *mut c_void {
self.inner.lock().context.context as *mut _
self.inner.lock().context.context.cast()
}
/// Obtain a lock to the WGL context and get handle to the [`glow::Context`] that can be used to
@ -184,7 +184,7 @@ fn load_gl_func(name: &str, module: Option<HMODULE>) -> *const c_void {
fn get_extensions(extra: &Wgl, dc: HDC) -> HashSet<String> {
if extra.GetExtensionsStringARB.is_loaded() {
unsafe { CStr::from_ptr(extra.GetExtensionsStringARB(dc as *const _)) }
unsafe { CStr::from_ptr(extra.GetExtensionsStringARB(dc.cast())) }
.to_str()
.unwrap_or("")
} else {
@ -427,7 +427,7 @@ impl crate::Instance for Instance {
unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
profiling::scope!("Init OpenGL (WGL) Backend");
let opengl_module = unsafe { LoadLibraryA("opengl32.dll\0".as_ptr() as *const _) };
let opengl_module = unsafe { LoadLibraryA("opengl32.dll\0".as_ptr().cast()) };
if opengl_module.is_null() {
return Err(crate::InstanceError::with_source(
String::from("unable to load the OpenGL library"),
@ -472,7 +472,7 @@ impl crate::Instance for Instance {
0, // End of list
];
let context = unsafe {
extra.CreateContextAttribsARB(dc as *const _, ptr::null(), attributes.as_ptr())
extra.CreateContextAttribsARB(dc.cast(), ptr::null(), attributes.as_ptr())
};
if context.is_null() {
return Err(crate::InstanceError::with_source(
@ -481,7 +481,7 @@ impl crate::Instance for Instance {
));
}
WglContext {
context: context as *mut _,
context: context.cast_mut().cast(),
}
} else {
context

View File

@ -226,6 +226,7 @@
clippy::pattern_type_mismatch,
)]
#![warn(
clippy::ptr_as_ptr,
trivial_casts,
trivial_numeric_casts,
unsafe_op_in_unsafe_fn,

View File

@ -679,7 +679,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.set_vertex_bytes(
index as _,
(sizes.len() * WORD_SIZE) as u64,
sizes.as_ptr() as _,
sizes.as_ptr().cast(),
);
}
}
@ -713,7 +713,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.set_fragment_bytes(
index as _,
(sizes.len() * WORD_SIZE) as u64,
sizes.as_ptr() as _,
sizes.as_ptr().cast(),
);
}
}
@ -785,7 +785,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.set_bytes(
index as _,
(sizes.len() * WORD_SIZE) as u64,
sizes.as_ptr() as _,
sizes.as_ptr().cast(),
);
}
}
@ -827,21 +827,21 @@ impl crate::CommandEncoder for super::CommandEncoder {
self.state.compute.as_ref().unwrap().set_bytes(
layout.push_constants_infos.cs.unwrap().buffer_index as _,
(layout.total_push_constants as usize * WORD_SIZE) as _,
state_pc.as_ptr() as _,
state_pc.as_ptr().cast(),
)
}
if stages.contains(wgt::ShaderStages::VERTEX) {
self.state.render.as_ref().unwrap().set_vertex_bytes(
layout.push_constants_infos.vs.unwrap().buffer_index as _,
(layout.total_push_constants as usize * WORD_SIZE) as _,
state_pc.as_ptr() as _,
state_pc.as_ptr().cast(),
)
}
if stages.contains(wgt::ShaderStages::FRAGMENT) {
self.state.render.as_ref().unwrap().set_fragment_bytes(
layout.push_constants_infos.fs.unwrap().buffer_index as _,
(layout.total_push_constants as usize * WORD_SIZE) as _,
state_pc.as_ptr() as _,
state_pc.as_ptr().cast(),
)
}
}
@ -895,7 +895,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.set_vertex_bytes(
index as _,
(sizes.len() * WORD_SIZE) as u64,
sizes.as_ptr() as _,
sizes.as_ptr().cast(),
);
}
}
@ -907,7 +907,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.set_fragment_bytes(
index as _,
(sizes.len() * WORD_SIZE) as u64,
sizes.as_ptr() as _,
sizes.as_ptr().cast(),
);
}
}
@ -956,7 +956,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.set_vertex_bytes(
index as _,
(sizes.len() * WORD_SIZE) as u64,
sizes.as_ptr() as _,
sizes.as_ptr().cast(),
);
}
}
@ -1212,7 +1212,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.set_bytes(
index as _,
(sizes.len() * WORD_SIZE) as u64,
sizes.as_ptr() as _,
sizes.as_ptr().cast(),
);
}

View File

@ -362,7 +362,7 @@ impl crate::Device for super::Device {
buffer: &super::Buffer,
range: crate::MemoryRange,
) -> DeviceResult<crate::BufferMapping> {
let ptr = buffer.raw.contents() as *mut u8;
let ptr = buffer.raw.contents().cast::<u8>();
assert!(!ptr.is_null());
Ok(crate::BufferMapping {
ptr: ptr::NonNull::new(unsafe { ptr.offset(range.start as isize) }).unwrap(),

View File

@ -833,7 +833,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
layout.raw,
conv::map_shader_stage(stages),
offset_bytes,
slice::from_raw_parts(data.as_ptr() as _, data.len() * 4),
slice::from_raw_parts(data.as_ptr().cast(), data.len() * 4),
)
};
}

View File

@ -343,7 +343,7 @@ impl gpu_alloc::MemoryDevice<vk::DeviceMemory> for super::DeviceShared {
self.raw
.map_memory(*memory, offset, size, vk::MemoryMapFlags::empty())
} {
Ok(ptr) => Ok(ptr::NonNull::new(ptr as *mut u8)
Ok(ptr) => Ok(ptr::NonNull::new(ptr.cast::<u8>())
.expect("Pointer to memory mapping must not be null")),
Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => {
Err(gpu_alloc::DeviceMapError::OutOfDeviceMemory)
@ -1513,7 +1513,7 @@ impl crate::Device for super::Device {
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a
// mutable reference which is also guaranteed to be valid for writes.
unsafe {
&mut *(to_init as *mut [MaybeUninit<T>] as *mut [T])
&mut *(ptr::from_mut::<[MaybeUninit<T>]>(to_init) as *mut [T])
}
};
(Self { remainder }, init)

View File

@ -23,7 +23,7 @@ unsafe extern "system" fn debug_utils_messenger_callback(
}
let cd = unsafe { &*callback_data_ptr };
let user_data = unsafe { &*(user_data as *mut super::DebugUtilsMessengerUserData) };
let user_data = unsafe { &*user_data.cast::<super::DebugUtilsMessengerUserData>() };
const VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912: i32 = 0x56146426;
if cd.message_id_number == VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912 {
@ -515,7 +515,7 @@ impl super::Instance {
}
let layer = unsafe {
crate::metal::Surface::get_metal_layer(view as *mut objc::runtime::Object, None)
crate::metal::Surface::get_metal_layer(view.cast::<objc::runtime::Object>(), None)
};
let surface = {
@ -523,7 +523,7 @@ impl super::Instance {
ext::metal_surface::Instance::new(&self.shared.entry, &self.shared.raw);
let vk_info = vk::MetalSurfaceCreateInfoEXT::default()
.flags(vk::MetalSurfaceCreateFlagsEXT::empty())
.layer(layer as *mut _);
.layer(layer.cast());
unsafe { metal_loader.create_metal_surface(&vk_info, None).unwrap() }
};

View File

@ -6,7 +6,7 @@
// We don't use syntax sugar where it's not necessary.
clippy::match_like_matches_macro,
)]
#![warn(missing_docs, unsafe_op_in_unsafe_fn)]
#![warn(clippy::ptr_as_ptr, missing_docs, unsafe_op_in_unsafe_fn)]
#[cfg(any(feature = "serde", test))]
use serde::Deserialize;
@ -7068,7 +7068,7 @@ impl DrawIndirectArgs {
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::mem::transmute(std::slice::from_raw_parts(
self as *const _ as *const u8,
std::ptr::from_ref(self).cast::<u8>(),
std::mem::size_of::<Self>(),
))
}
@ -7098,7 +7098,7 @@ impl DrawIndexedIndirectArgs {
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::mem::transmute(std::slice::from_raw_parts(
self as *const _ as *const u8,
std::ptr::from_ref(self).cast::<u8>(),
std::mem::size_of::<Self>(),
))
}
@ -7122,7 +7122,7 @@ impl DispatchIndirectArgs {
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::mem::transmute(std::slice::from_raw_parts(
self as *const _ as *const u8,
std::ptr::from_ref(self).cast::<u8>(),
std::mem::size_of::<Self>(),
))
}