From a1307b6ef8dbcf77c3479c56bd354de7bc297a2e Mon Sep 17 00:00:00 2001 From: Rua Date: Tue, 29 Oct 2024 19:39:08 +0100 Subject: [PATCH] Minimise unsafe block size, in library (#2592) * Minimise unsafe block size, in library * Missed one --- Cargo.toml | 5 +- .../command_buffer/commands/dynamic_state.rs | 2 +- vulkano-taskgraph/src/graph/execute.rs | 36 +- vulkano-taskgraph/src/lib.rs | 6 +- vulkano/src/acceleration_structure.rs | 17 +- vulkano/src/buffer/allocator.rs | 10 +- vulkano/src/buffer/mod.rs | 12 +- vulkano/src/buffer/subbuffer.rs | 8 +- vulkano/src/buffer/sys.rs | 38 +- vulkano/src/buffer/view.rs | 41 +- vulkano/src/command_buffer/allocator.rs | 10 +- vulkano/src/command_buffer/auto/builder.rs | 33 +- vulkano/src/command_buffer/auto/mod.rs | 465 +++++++++--------- .../src/command_buffer/commands/bind_push.rs | 26 +- vulkano/src/command_buffer/commands/clear.rs | 8 +- vulkano/src/command_buffer/commands/copy.rs | 12 +- vulkano/src/command_buffer/commands/debug.rs | 4 +- .../command_buffer/commands/dynamic_state.rs | 78 +-- .../src/command_buffer/commands/pipeline.rs | 50 +- vulkano/src/command_buffer/commands/query.rs | 8 +- .../command_buffer/commands/render_pass.rs | 12 +- .../src/command_buffer/commands/secondary.rs | 4 +- vulkano/src/command_buffer/mod.rs | 32 +- vulkano/src/command_buffer/pool.rs | 22 +- vulkano/src/command_buffer/traits.rs | 31 +- vulkano/src/deferred.rs | 14 +- vulkano/src/descriptor_set/allocator.rs | 9 +- vulkano/src/descriptor_set/layout.rs | 18 +- vulkano/src/descriptor_set/mod.rs | 4 +- vulkano/src/descriptor_set/pool.rs | 48 +- vulkano/src/device/mod.rs | 106 ++-- vulkano/src/device/physical.rs | 249 +++++----- vulkano/src/device/private_data.rs | 39 +- vulkano/src/device/queue.rs | 57 +-- vulkano/src/display.rs | 116 ++--- vulkano/src/image/mod.rs | 10 +- vulkano/src/image/sampler/mod.rs | 30 +- vulkano/src/image/sampler/ycbcr.rs | 47 +- vulkano/src/image/sys.rs | 216 ++++---- vulkano/src/image/view.rs | 10 +- vulkano/src/instance/debug.rs | 73 ++- vulkano/src/instance/mod.rs | 64 ++- vulkano/src/library.rs | 50 +- vulkano/src/memory/allocator/mod.rs | 4 +- vulkano/src/memory/device_memory.rs | 85 ++-- vulkano/src/pipeline/cache.rs | 76 +-- vulkano/src/pipeline/compute.rs | 28 +- vulkano/src/pipeline/graphics/mod.rs | 16 +- vulkano/src/pipeline/graphics/subpass.rs | 15 +- .../src/pipeline/graphics/vertex_input/mod.rs | 9 +- vulkano/src/pipeline/layout.rs | 8 +- vulkano/src/query.rs | 36 +- vulkano/src/render_pass/framebuffer.rs | 26 +- vulkano/src/render_pass/mod.rs | 90 ++-- vulkano/src/shader/mod.rs | 30 +- vulkano/src/swapchain/acquire_present.rs | 130 +++-- vulkano/src/swapchain/mod.rs | 244 +++++---- vulkano/src/swapchain/surface.rs | 61 +-- vulkano/src/sync/event.rs | 87 ++-- vulkano/src/sync/fence.rs | 53 +- vulkano/src/sync/future/fence_signal.rs | 239 ++++----- vulkano/src/sync/future/semaphore_signal.rs | 147 +++--- vulkano/src/sync/semaphore.rs | 35 +- 63 files changed, 1749 insertions(+), 1800 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9b6748df..a1b2011f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,11 +83,12 @@ rand = "0.8" ron = "0.8" [workspace.lints] -rust.missing_docs = "allow" # TODO: warn eventually +rust.missing_docs = "allow" # TODO: warn eventually rust.rust_2018_idioms = { level = "warn", priority = -1 } rust.rust_2024_compatibility = { level = "allow", priority = -1 } # TODO: warn eventually clippy.borrow_as_ptr = "warn" -clippy.missing_safety_doc = "allow" # TODO: warn eventually +clippy.missing_safety_doc = "allow" # TODO: warn eventually +clippy.multiple_unsafe_ops_per_block = "warn" clippy.ptr_as_ptr = "warn" clippy.ptr_cast_constness = "warn" # clippy.ref_as_ptr = "warn" # TODO: enable once it's stable diff --git a/vulkano-taskgraph/src/command_buffer/commands/dynamic_state.rs b/vulkano-taskgraph/src/command_buffer/commands/dynamic_state.rs index 79ae0b82..7867bec5 100644 --- a/vulkano-taskgraph/src/command_buffer/commands/dynamic_state.rs +++ b/vulkano-taskgraph/src/command_buffer/commands/dynamic_state.rs @@ -780,7 +780,7 @@ impl RecordingCommandBuffer<'_> { fragment_size: [u32; 2], combiner_ops: [FragmentShadingRateCombinerOp; 2], ) -> Result<&mut Self> { - unsafe { Ok(self.set_fragment_shading_rate_unchecked(fragment_size, combiner_ops)) } + Ok(unsafe { self.set_fragment_shading_rate_unchecked(fragment_size, combiner_ops) }) } pub unsafe fn set_fragment_shading_rate_unchecked( diff --git a/vulkano-taskgraph/src/graph/execute.rs b/vulkano-taskgraph/src/graph/execute.rs index 61eb5c53..d433afdd 100644 --- a/vulkano-taskgraph/src/graph/execute.rs +++ b/vulkano-taskgraph/src/graph/execute.rs @@ -566,7 +566,8 @@ impl ExecutableTaskGraph { ObjectType::Buffer => { // SAFETY: The caller must ensure that `resource_map` maps the virtual IDs // exhaustively. - let state = unsafe { resource_map.buffer_unchecked(id.parametrize()) }; + let id_p = unsafe { id.parametrize() }; + let state = unsafe { resource_map.buffer_unchecked(id_p) }; let access = BufferAccess::from_masks( access.stage_mask, access.access_mask, @@ -577,7 +578,8 @@ impl ExecutableTaskGraph { ObjectType::Image => { // SAFETY: The caller must ensure that `resource_map` maps the virtual IDs // exhaustively. - let state = unsafe { resource_map.image_unchecked(id.parametrize()) }; + let id_p = unsafe { id.parametrize() }; + let state = unsafe { resource_map.image_unchecked(id_p) }; let access = ImageAccess::from_masks( access.stage_mask, access.access_mask, @@ -589,7 +591,8 @@ impl ExecutableTaskGraph { ObjectType::Swapchain => { // SAFETY: The caller must ensure that `resource_map` maps the virtual IDs // exhaustively. - let state = unsafe { resource_map.swapchain_unchecked(id.parametrize()) }; + let id_p = unsafe { id.parametrize() }; + let state = unsafe { resource_map.swapchain_unchecked(id_p) }; let access = ImageAccess::from_masks( access.stage_mask, access.access_mask, @@ -1670,17 +1673,26 @@ impl<'a> ResourceMap<'a> { *slot = match physical_id.object_type() { // SAFETY: We own an `epoch::Guard`. - ObjectType::Buffer => <*const _>::cast(unsafe { - physical_resources.buffer_unprotected(physical_id.parametrize()) - }?), + ObjectType::Buffer => { + let physical_id_p = unsafe { physical_id.parametrize() }; + <*const _>::cast(unsafe { + physical_resources.buffer_unprotected(physical_id_p) + }?) + } // SAFETY: We own an `epoch::Guard`. - ObjectType::Image => <*const _>::cast(unsafe { - physical_resources.image_unprotected(physical_id.parametrize()) - }?), + ObjectType::Image => { + let physical_id_p = unsafe { physical_id.parametrize() }; + <*const _>::cast(unsafe { + physical_resources.image_unprotected(physical_id_p) + }?) + } // SAFETY: We own an `epoch::Guard`. - ObjectType::Swapchain => <*const _>::cast(unsafe { - physical_resources.swapchain_unprotected(physical_id.parametrize()) - }?), + ObjectType::Swapchain => { + let physical_id_p = unsafe { physical_id.parametrize() }; + <*const _>::cast(unsafe { + physical_resources.swapchain_unprotected(physical_id_p) + }?) + } _ => unreachable!(), }; } diff --git a/vulkano-taskgraph/src/lib.rs b/vulkano-taskgraph/src/lib.rs index c00f4bb4..7c22a04d 100644 --- a/vulkano-taskgraph/src/lib.rs +++ b/vulkano-taskgraph/src/lib.rs @@ -389,7 +389,8 @@ impl<'a> TaskContext<'a> { let mapped_slice = subbuffer.mapped_slice().unwrap(); // SAFETY: The caller must ensure that access to the data is synchronized. - let data = unsafe { &*T::ptr_from_slice(mapped_slice) }; + let data_ptr = unsafe { T::ptr_from_slice(mapped_slice) }; + let data = unsafe { &*data_ptr }; Ok(data) } @@ -492,7 +493,8 @@ impl<'a> TaskContext<'a> { let mapped_slice = subbuffer.mapped_slice().unwrap(); // SAFETY: The caller must ensure that access to the data is synchronized. - let data = unsafe { &mut *T::ptr_from_slice(mapped_slice) }; + let data_ptr = unsafe { T::ptr_from_slice(mapped_slice) }; + let data = unsafe { &mut *data_ptr }; Ok(data) } diff --git a/vulkano/src/acceleration_structure.rs b/vulkano/src/acceleration_structure.rs index 8af94151..422bfe18 100644 --- a/vulkano/src/acceleration_structure.rs +++ b/vulkano/src/acceleration_structure.rs @@ -245,8 +245,8 @@ impl AccelerationStructure { pub fn device_address(&self) -> NonNullDeviceAddress { let info_vk = ash::vk::AccelerationStructureDeviceAddressInfoKHR::default() .acceleration_structure(self.handle); + let fns = self.device.fns(); let ptr = unsafe { - let fns = self.device.fns(); (fns.khr_acceleration_structure .get_acceleration_structure_device_address_khr)( self.device.handle(), &info_vk @@ -260,8 +260,8 @@ impl AccelerationStructure { impl Drop for AccelerationStructure { #[inline] fn drop(&mut self) { + let fns = self.device.fns(); unsafe { - let fns = self.device.fns(); (fns.khr_acceleration_structure .destroy_acceleration_structure_khr)( self.device.handle(), self.handle, ptr::null() @@ -917,13 +917,16 @@ impl AccelerationStructureGeometryTrianglesData { ]) })?; - if unsafe { - !device + let format_properties = unsafe { + device .physical_device() .format_properties_unchecked(vertex_format) - .buffer_features - .intersects(FormatFeatures::ACCELERATION_STRUCTURE_VERTEX_BUFFER) - } { + }; + + if !format_properties + .buffer_features + .intersects(FormatFeatures::ACCELERATION_STRUCTURE_VERTEX_BUFFER) + { return Err(Box::new(ValidationError { context: "vertex_format".into(), problem: "format features do not contain \ diff --git a/vulkano/src/buffer/allocator.rs b/vulkano/src/buffer/allocator.rs index 9139f2da..549c6009 100644 --- a/vulkano/src/buffer/allocator.rs +++ b/vulkano/src/buffer/allocator.rs @@ -182,7 +182,8 @@ where /// The next time you allocate a subbuffer, a new arena will be allocated with the new size, /// and all subsequently allocated arenas will also share the new size. pub fn set_arena_size(&self, size: DeviceSize) { - let state = unsafe { &mut *self.state.get() }; + let state_ptr = self.state.get(); + let state = unsafe { &mut *state_ptr }; state.arena_size = size; state.arena = None; state.reserve = None; @@ -195,7 +196,8 @@ where /// this has no effect. pub fn reserve(&self, size: DeviceSize) -> Result<(), MemoryAllocatorError> { if size > self.arena_size() { - let state = unsafe { &mut *self.state.get() }; + let state_ptr = self.state.get(); + let state = unsafe { &mut *state_ptr }; state.arena_size = size; state.reserve = None; state.arena = Some(state.next_arena()?); @@ -211,7 +213,9 @@ where { let layout = T::LAYOUT.unwrap_sized(); - unsafe { &mut *self.state.get() } + let state_ptr = self.state.get(); + let state = unsafe { &mut *state_ptr }; + state .allocate(layout) .map(|subbuffer| unsafe { subbuffer.reinterpret_unchecked() }) } diff --git a/vulkano/src/buffer/mod.rs b/vulkano/src/buffer/mod.rs index e6fab01f..a6f15e66 100644 --- a/vulkano/src/buffer/mod.rs +++ b/vulkano/src/buffer/mod.rs @@ -405,12 +405,10 @@ impl Buffer { let allocation = unsafe { ResourceMemory::from_allocation(allocator, allocation) }; // SAFETY: we just created this raw buffer and hasn't bound any memory to it. - let buffer = unsafe { - raw_buffer.bind_memory(allocation).map_err(|(err, _, _)| { - err.map(AllocateBufferError::BindMemory) - .map_validation(|err| err.add_context("RawBuffer::bind_memory")) - })? - }; + let buffer = unsafe { raw_buffer.bind_memory(allocation) }.map_err(|(err, _, _)| { + err.map(AllocateBufferError::BindMemory) + .map_validation(|err| err.add_context("RawBuffer::bind_memory")) + })?; Ok(Arc::new(buffer)) } @@ -472,7 +470,7 @@ impl Buffer { pub fn device_address(&self) -> Result> { self.validate_device_address()?; - unsafe { Ok(self.device_address_unchecked()) } + Ok(unsafe { self.device_address_unchecked() }) } fn validate_device_address(&self) -> Result<(), Box> { diff --git a/vulkano/src/buffer/subbuffer.rs b/vulkano/src/buffer/subbuffer.rs index e122af42..f3eb12f5 100644 --- a/vulkano/src/buffer/subbuffer.rs +++ b/vulkano/src/buffer/subbuffer.rs @@ -377,7 +377,8 @@ where } // SAFETY: `Subbuffer` guarantees that its contents are laid out correctly for `T`. - let data = unsafe { &*T::ptr_from_slice(mapped_slice) }; + let data_ptr = unsafe { T::ptr_from_slice(mapped_slice) }; + let data = unsafe { &*data_ptr }; Ok(BufferReadGuard { subbuffer: self, @@ -464,7 +465,8 @@ where } // SAFETY: `Subbuffer` guarantees that its contents are laid out correctly for `T`. - let data = unsafe { &mut *T::ptr_from_slice(mapped_slice) }; + let data_ptr = unsafe { T::ptr_from_slice(mapped_slice) }; + let data = unsafe { &mut *data_ptr }; Ok(BufferWriteGuard { subbuffer: self, @@ -710,7 +712,7 @@ impl Drop for BufferWriteGuard<'_, T> { _ne: crate::NonExhaustive(()), }; - unsafe { allocation.flush_range_unchecked(memory_range).unwrap() }; + unsafe { allocation.flush_range_unchecked(memory_range) }.unwrap(); } let mut state = self.subbuffer.buffer().state(); diff --git a/vulkano/src/buffer/sys.rs b/vulkano/src/buffer/sys.rs index f4d24ef8..f063792d 100644 --- a/vulkano/src/buffer/sys.rs +++ b/vulkano/src/buffer/sys.rs @@ -58,7 +58,7 @@ impl RawBuffer { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -195,33 +195,37 @@ impl RawBuffer { let mut memory_requirements2_vk = MemoryRequirements::to_mut_vk2(&mut memory_requirements2_extensions_vk); - unsafe { - let fns = device.fns(); + let fns = device.fns(); - if device.api_version() >= Version::V1_1 - || device.enabled_extensions().khr_get_memory_requirements2 - { - if device.api_version() >= Version::V1_1 { + if device.api_version() >= Version::V1_1 + || device.enabled_extensions().khr_get_memory_requirements2 + { + if device.api_version() >= Version::V1_1 { + unsafe { (fns.v1_1.get_buffer_memory_requirements2)( device.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } else { + ) + }; + } else { + unsafe { (fns.khr_get_memory_requirements2 .get_buffer_memory_requirements2_khr)( device.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } - } else { + ) + }; + } + } else { + unsafe { (fns.v1_0.get_buffer_memory_requirements)( device.handle(), handle, &mut memory_requirements2_vk.memory_requirements, - ); - } + ) + }; } // Unborrow @@ -556,10 +560,8 @@ impl Drop for RawBuffer { #[inline] fn drop(&mut self) { if self.needs_destruction { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_buffer)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_buffer)(self.device.handle(), self.handle, ptr::null()) }; } } } diff --git a/vulkano/src/buffer/view.rs b/vulkano/src/buffer/view.rs index d969af62..aac7c609 100644 --- a/vulkano/src/buffer/view.rs +++ b/vulkano/src/buffer/view.rs @@ -71,7 +71,7 @@ impl BufferView { let subbuffer = subbuffer.into_bytes(); Self::validate_new(&subbuffer, &create_info)?; - unsafe { Ok(Self::new_unchecked(subbuffer, create_info)?) } + Ok(unsafe { Self::new_unchecked(subbuffer, create_info) }?) } fn validate_new( @@ -89,12 +89,9 @@ impl BufferView { let buffer = subbuffer.buffer(); let properties = device.physical_device().properties(); - let format_features = unsafe { - device - .physical_device() - .format_properties_unchecked(format) - .buffer_features - }; + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + let format_features = format_properties.buffer_features; if !buffer .usage() @@ -290,18 +287,20 @@ impl BufferView { let device = subbuffer.device(); let create_info_vk = create_info.to_vk(subbuffer.as_bytes()); - let handle = unsafe { - let fns = device.fns(); + let fns = device.fns(); + let handle = { let mut output = MaybeUninit::uninit(); - (fns.v1_0.create_buffer_view)( - device.handle(), - &create_info_vk, - ptr::null(), - output.as_mut_ptr(), - ) + unsafe { + (fns.v1_0.create_buffer_view)( + device.handle(), + &create_info_vk, + ptr::null(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; Ok(Self::from_handle(subbuffer, handle, create_info)) @@ -320,13 +319,13 @@ impl BufferView { ) -> Arc { let &BufferViewCreateInfo { format, _ne: _ } = &create_info; let size = subbuffer.size(); - let format_features = unsafe { + let format_properties = unsafe { subbuffer .device() .physical_device() .format_properties_unchecked(format) - .buffer_features }; + let format_features = format_properties.buffer_features; Arc::new(BufferView { handle, @@ -366,14 +365,14 @@ impl BufferView { impl Drop for BufferView { #[inline] fn drop(&mut self) { + let fns = self.subbuffer.device().fns(); unsafe { - let fns = self.subbuffer.device().fns(); (fns.v1_0.destroy_buffer_view)( self.subbuffer.device().handle(), self.handle, ptr::null(), - ); - } + ) + }; } } diff --git a/vulkano/src/command_buffer/allocator.rs b/vulkano/src/command_buffer/allocator.rs index 15e19f69..26380729 100644 --- a/vulkano/src/command_buffer/allocator.rs +++ b/vulkano/src/command_buffer/allocator.rs @@ -216,7 +216,9 @@ impl StandardCommandBufferAllocator { queue_family_index: u32, flags: CommandPoolResetFlags, ) -> Result<(), Validated> { - if let Some(entry) = unsafe { &mut *self.entry(queue_family_index) }.as_mut() { + let entry_ptr = self.entry(queue_family_index); + + if let Some(entry) = unsafe { &mut *entry_ptr }.as_mut() { entry.try_reset_pool(flags) } else { Ok(()) @@ -234,7 +236,8 @@ impl StandardCommandBufferAllocator { /// - Panics if `queue_family_index` is not less than the number of queue families. #[inline] pub fn clear(&self, queue_family_index: u32) { - unsafe { *self.entry(queue_family_index) = None }; + let entry_ptr = self.entry(queue_family_index); + unsafe { *entry_ptr = None }; } fn entry(&self, queue_family_index: u32) -> *mut Option { @@ -271,7 +274,8 @@ unsafe impl CommandBufferAllocator for StandardCommandBufferAllocator { }))?; } - let entry = unsafe { &mut *self.entry(queue_family_index) }; + let entry_ptr = self.entry(queue_family_index); + let entry = unsafe { &mut *entry_ptr }; if entry.is_none() { *entry = Some(Entry::new( diff --git a/vulkano/src/command_buffer/auto/builder.rs b/vulkano/src/command_buffer/auto/builder.rs index 13062f26..ca953227 100644 --- a/vulkano/src/command_buffer/auto/builder.rs +++ b/vulkano/src/command_buffer/auto/builder.rs @@ -117,7 +117,7 @@ impl AutoCommandBufferBuilder { pub fn build(self) -> Result, Validated> { self.validate_end()?; - let (inner, keep_alive_objects, resources_usage, _) = unsafe { self.end_unchecked()? }; + let (inner, keep_alive_objects, resources_usage, _) = unsafe { self.end_unchecked() }?; Ok(Arc::new(PrimaryAutoCommandBuffer { inner, @@ -177,7 +177,7 @@ impl AutoCommandBufferBuilder { pub fn build(self) -> Result, Validated> { self.validate_end()?; - let (inner, keep_alive_objects, _, resources_usage) = unsafe { self.end_unchecked()? }; + let (inner, keep_alive_objects, _, resources_usage) = unsafe { self.end_unchecked() }?; let submit_state = match inner.usage() { CommandBufferUsage::MultipleSubmit => SubmitState::ExclusiveUse { @@ -331,15 +331,14 @@ impl AutoCommandBufferBuilder { for (command_index, (_, record_func)) in self.commands.iter().enumerate() { if let Some(barriers) = barriers.remove(&command_index) { for dependency_info in barriers { - unsafe { - #[cfg(debug_assertions)] - self.inner - .pipeline_barrier(&dependency_info) - .expect("bug in Vulkano"); + #[cfg(debug_assertions)] + unsafe { self.inner.pipeline_barrier(&dependency_info) } + .expect("bug in Vulkano"); - #[cfg(not(debug_assertions))] - self.inner.pipeline_barrier_unchecked(&dependency_info); - } + #[cfg(not(debug_assertions))] + unsafe { + self.inner.pipeline_barrier_unchecked(&dependency_info) + }; } } @@ -349,15 +348,13 @@ impl AutoCommandBufferBuilder { // Record final barriers if let Some(final_barriers) = barriers.remove(&final_barrier_index) { for dependency_info in final_barriers { - unsafe { - #[cfg(debug_assertions)] - self.inner - .pipeline_barrier(&dependency_info) - .expect("bug in Vulkano"); + #[cfg(debug_assertions)] + unsafe { self.inner.pipeline_barrier(&dependency_info) }.expect("bug in Vulkano"); - #[cfg(not(debug_assertions))] - self.inner.pipeline_barrier_unchecked(&dependency_info); - } + #[cfg(not(debug_assertions))] + unsafe { + self.inner.pipeline_barrier_unchecked(&dependency_info) + }; } } diff --git a/vulkano/src/command_buffer/auto/mod.rs b/vulkano/src/command_buffer/auto/mod.rs index f4144529..1e5008c5 100644 --- a/vulkano/src/command_buffer/auto/mod.rs +++ b/vulkano/src/command_buffer/auto/mod.rs @@ -644,67 +644,51 @@ mod tests { #[test] fn secondary_conflicting_writes() { - unsafe { - let (device, queue) = gfx_dev_and_queue!(); + let (device, queue) = gfx_dev_and_queue!(); - let cb_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - StandardCommandBufferAllocatorCreateInfo { - secondary_buffer_count: 1, - ..Default::default() - }, - )); - let cbb = AutoCommandBufferBuilder::primary( - cb_allocator.clone(), - queue.queue_family_index(), - CommandBufferUsage::OneTimeSubmit, - ) + let cb_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + StandardCommandBufferAllocatorCreateInfo { + secondary_buffer_count: 1, + ..Default::default() + }, + )); + let cbb = AutoCommandBufferBuilder::primary( + cb_allocator.clone(), + queue.queue_family_index(), + CommandBufferUsage::OneTimeSubmit, + ) + .unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device)); + // Create a tiny test buffer + let buffer = Buffer::from_data( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::TRANSFER_DST, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + 0u32, + ) + .unwrap(); + + cbb.build() + .unwrap() + .execute(queue.clone()) + .unwrap() + .then_signal_fence_and_flush() + .unwrap() + .wait(None) .unwrap(); - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device)); - // Create a tiny test buffer - let buffer = Buffer::from_data( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::TRANSFER_DST, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - 0u32, - ) - .unwrap(); - - cbb.build() - .unwrap() - .execute(queue.clone()) - .unwrap() - .then_signal_fence_and_flush() - .unwrap() - .wait(None) - .unwrap(); - - // Two secondary command buffers that both write to the buffer - let secondary = (0..2) - .map(|_| { - let mut builder = AutoCommandBufferBuilder::secondary( - cb_allocator.clone(), - queue.queue_family_index(), - CommandBufferUsage::SimultaneousUse, - Default::default(), - ) - .unwrap(); - builder - .fill_buffer(buffer.clone().into_slice(), 42) - .unwrap(); - builder.build().unwrap() - }) - .collect::>(); - - { + // Two secondary command buffers that both write to the buffer + let secondary = (0..2) + .map(|_| { let mut builder = AutoCommandBufferBuilder::secondary( cb_allocator.clone(), queue.queue_family_index(), @@ -712,224 +696,243 @@ mod tests { Default::default(), ) .unwrap(); + builder + .fill_buffer(buffer.clone().into_slice(), 42) + .unwrap(); + builder.build().unwrap() + }) + .collect::>(); - // Add both secondary command buffers using separate execute_commands calls. - secondary.iter().cloned().for_each(|secondary| { - builder.execute_commands_unchecked([secondary as _].into_iter().collect()); - }); + { + let mut builder = AutoCommandBufferBuilder::secondary( + cb_allocator.clone(), + queue.queue_family_index(), + CommandBufferUsage::SimultaneousUse, + Default::default(), + ) + .unwrap(); - let _primary = builder.build().unwrap(); - /* - let names = primary._commands.iter().map(|c| c.name).collect::>(); + // Add both secondary command buffers using separate execute_commands calls. + secondary.iter().cloned().for_each(|secondary| { + unsafe { + builder.execute_commands_unchecked([secondary as _].into_iter().collect()) + }; + }); - // Ensure that the builder added a barrier between the two writes - assert_eq!(&names, &["execute_commands", "execute_commands"]); - assert_eq!(&primary._barriers, &[0, 1]); - */ - } + let _primary = builder.build().unwrap(); + /* + let names = primary._commands.iter().map(|c| c.name).collect::>(); - { - let mut builder = AutoCommandBufferBuilder::secondary( - cb_allocator, - queue.queue_family_index(), - CommandBufferUsage::SimultaneousUse, - Default::default(), - ) - .unwrap(); + // Ensure that the builder added a barrier between the two writes + assert_eq!(&names, &["execute_commands", "execute_commands"]); + assert_eq!(&primary._barriers, &[0, 1]); + */ + } - // Add a single execute_commands for all secondary command buffers at once + { + let mut builder = AutoCommandBufferBuilder::secondary( + cb_allocator, + queue.queue_family_index(), + CommandBufferUsage::SimultaneousUse, + Default::default(), + ) + .unwrap(); + + // Add a single execute_commands for all secondary command buffers at once + unsafe { builder.execute_commands_unchecked( secondary .into_iter() .map(|secondary| secondary as _) .collect(), - ); - } + ) + }; } } #[test] fn vertex_buffer_binding() { - unsafe { - let (device, queue) = gfx_dev_and_queue!(); + let (device, queue) = gfx_dev_and_queue!(); - let cb_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - let mut sync = AutoCommandBufferBuilder::primary( - cb_allocator, - queue.queue_family_index(), - CommandBufferUsage::MultipleSubmit, - ) - .unwrap(); + let cb_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + let mut sync = AutoCommandBufferBuilder::primary( + cb_allocator, + queue.queue_family_index(), + CommandBufferUsage::MultipleSubmit, + ) + .unwrap(); - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device)); - let buf = Buffer::from_data( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - 0u32, - ) - .unwrap(); - sync.bind_vertex_buffers_unchecked(1, buf); + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device)); + let buf = Buffer::from_data( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + 0u32, + ) + .unwrap(); + unsafe { sync.bind_vertex_buffers_unchecked(1, buf) }; - assert!(!sync.builder_state.vertex_buffers.contains_key(&0)); - assert!(sync.builder_state.vertex_buffers.contains_key(&1)); - assert!(!sync.builder_state.vertex_buffers.contains_key(&2)); - } + assert!(!sync.builder_state.vertex_buffers.contains_key(&0)); + assert!(sync.builder_state.vertex_buffers.contains_key(&1)); + assert!(!sync.builder_state.vertex_buffers.contains_key(&2)); } #[test] fn descriptor_set_binding() { - unsafe { - let (device, queue) = gfx_dev_and_queue!(); + let (device, queue) = gfx_dev_and_queue!(); - let cb_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - let mut sync = AutoCommandBufferBuilder::primary( - cb_allocator, - queue.queue_family_index(), - CommandBufferUsage::MultipleSubmit, - ) - .unwrap(); - let set_layout = DescriptorSetLayout::new( - device.clone(), - DescriptorSetLayoutCreateInfo { - bindings: [( - 0, - DescriptorSetLayoutBinding { - stages: ShaderStages::all_graphics(), - ..DescriptorSetLayoutBinding::descriptor_type(DescriptorType::Sampler) - }, - )] - .into(), - ..Default::default() - }, - ) - .unwrap(); - let pipeline_layout = PipelineLayout::new( - device.clone(), - PipelineLayoutCreateInfo { - set_layouts: [set_layout.clone(), set_layout.clone()].into(), - ..Default::default() - }, - ) - .unwrap(); - - let ds_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - - let set = DescriptorSet::new( - ds_allocator.clone(), - set_layout.clone(), - [WriteDescriptorSet::sampler( + let cb_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + let mut sync = AutoCommandBufferBuilder::primary( + cb_allocator, + queue.queue_family_index(), + CommandBufferUsage::MultipleSubmit, + ) + .unwrap(); + let set_layout = DescriptorSetLayout::new( + device.clone(), + DescriptorSetLayoutCreateInfo { + bindings: [( 0, - Sampler::new(device.clone(), SamplerCreateInfo::simple_repeat_linear()) - .unwrap(), - )], - [], - ) - .unwrap(); + DescriptorSetLayoutBinding { + stages: ShaderStages::all_graphics(), + ..DescriptorSetLayoutBinding::descriptor_type(DescriptorType::Sampler) + }, + )] + .into(), + ..Default::default() + }, + ) + .unwrap(); + let pipeline_layout = PipelineLayout::new( + device.clone(), + PipelineLayoutCreateInfo { + set_layouts: [set_layout.clone(), set_layout.clone()].into(), + ..Default::default() + }, + ) + .unwrap(); + let ds_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + + let set = DescriptorSet::new( + ds_allocator.clone(), + set_layout.clone(), + [WriteDescriptorSet::sampler( + 0, + Sampler::new(device.clone(), SamplerCreateInfo::simple_repeat_linear()).unwrap(), + )], + [], + ) + .unwrap(); + + unsafe { sync.bind_descriptor_sets_unchecked( PipelineBindPoint::Graphics, pipeline_layout.clone(), 1, set.clone(), - ); + ) + }; - assert!(!sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Compute) - .map_or(false, |state| state.descriptor_sets.contains_key(&0))); - assert!(!sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Graphics) - .map_or(false, |state| state.descriptor_sets.contains_key(&0))); - assert!(sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Graphics) - .map_or(false, |state| state.descriptor_sets.contains_key(&1))); - assert!(!sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Graphics) - .map_or(false, |state| state.descriptor_sets.contains_key(&2))); + assert!(!sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Compute) + .map_or(false, |state| state.descriptor_sets.contains_key(&0))); + assert!(!sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Graphics) + .map_or(false, |state| state.descriptor_sets.contains_key(&0))); + assert!(sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Graphics) + .map_or(false, |state| state.descriptor_sets.contains_key(&1))); + assert!(!sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Graphics) + .map_or(false, |state| state.descriptor_sets.contains_key(&2))); + unsafe { sync.bind_descriptor_sets_unchecked( PipelineBindPoint::Graphics, pipeline_layout, 0, set, - ); - - assert!(sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Graphics) - .map_or(false, |state| state.descriptor_sets.contains_key(&0))); - assert!(sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Graphics) - .map_or(false, |state| state.descriptor_sets.contains_key(&1))); - - let pipeline_layout = PipelineLayout::new( - device.clone(), - PipelineLayoutCreateInfo { - set_layouts: [ - DescriptorSetLayout::new(device.clone(), Default::default()).unwrap(), - set_layout.clone(), - ] - .into(), - ..Default::default() - }, ) - .unwrap(); + }; - let set = DescriptorSet::new( - ds_allocator, - set_layout, - [WriteDescriptorSet::sampler( - 0, - Sampler::new(device, SamplerCreateInfo::simple_repeat_linear()).unwrap(), - )], - [], - ) - .unwrap(); + assert!(sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Graphics) + .map_or(false, |state| state.descriptor_sets.contains_key(&0))); + assert!(sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Graphics) + .map_or(false, |state| state.descriptor_sets.contains_key(&1))); + let pipeline_layout = PipelineLayout::new( + device.clone(), + PipelineLayoutCreateInfo { + set_layouts: [ + DescriptorSetLayout::new(device.clone(), Default::default()).unwrap(), + set_layout.clone(), + ] + .into(), + ..Default::default() + }, + ) + .unwrap(); + + let set = DescriptorSet::new( + ds_allocator, + set_layout, + [WriteDescriptorSet::sampler( + 0, + Sampler::new(device, SamplerCreateInfo::simple_repeat_linear()).unwrap(), + )], + [], + ) + .unwrap(); + + unsafe { sync.bind_descriptor_sets_unchecked( PipelineBindPoint::Graphics, pipeline_layout, 1, set, - ); + ) + }; - assert!(!sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Graphics) - .map_or(false, |state| state.descriptor_sets.contains_key(&0))); - assert!(sync - .builder_state - .descriptor_sets - .get(&PipelineBindPoint::Graphics) - .map_or(false, |state| state.descriptor_sets.contains_key(&1))); - } + assert!(!sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Graphics) + .map_or(false, |state| state.descriptor_sets.contains_key(&0))); + assert!(sync + .builder_state + .descriptor_sets + .get(&PipelineBindPoint::Graphics) + .map_or(false, |state| state.descriptor_sets.contains_key(&1))); } } diff --git a/vulkano/src/command_buffer/commands/bind_push.rs b/vulkano/src/command_buffer/commands/bind_push.rs index 7ecbbdfc..37d54ac6 100644 --- a/vulkano/src/command_buffer/commands/bind_push.rs +++ b/vulkano/src/command_buffer/commands/bind_push.rs @@ -38,14 +38,14 @@ impl AutoCommandBufferBuilder { &descriptor_sets, )?; - unsafe { - Ok(self.bind_descriptor_sets_unchecked( + Ok(unsafe { + self.bind_descriptor_sets_unchecked( pipeline_bind_point, pipeline_layout, first_set, descriptor_sets, - )) - } + ) + }) } // TODO: The validation here is somewhat duplicated because of how different the parameters are @@ -269,7 +269,7 @@ impl AutoCommandBufferBuilder { let index_buffer = index_buffer.into(); self.validate_bind_index_buffer(&index_buffer)?; - unsafe { Ok(self.bind_index_buffer_unchecked(index_buffer)) } + Ok(unsafe { self.bind_index_buffer_unchecked(index_buffer) }) } fn validate_bind_index_buffer( @@ -306,7 +306,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_bind_pipeline_compute(&pipeline)?; - unsafe { Ok(self.bind_pipeline_compute_unchecked(pipeline)) } + Ok(unsafe { self.bind_pipeline_compute_unchecked(pipeline) }) } fn validate_bind_pipeline_compute( @@ -342,7 +342,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_bind_pipeline_graphics(&pipeline)?; - unsafe { Ok(self.bind_pipeline_graphics_unchecked(pipeline)) } + Ok(unsafe { self.bind_pipeline_graphics_unchecked(pipeline) }) } fn validate_bind_pipeline_graphics( @@ -387,7 +387,7 @@ impl AutoCommandBufferBuilder { let vertex_buffers = vertex_buffers.into_vec(); self.validate_bind_vertex_buffers(first_binding, &vertex_buffers)?; - unsafe { Ok(self.bind_vertex_buffers_unchecked(first_binding, vertex_buffers)) } + Ok(unsafe { self.bind_vertex_buffers_unchecked(first_binding, vertex_buffers) }) } fn validate_bind_vertex_buffers( @@ -444,7 +444,7 @@ impl AutoCommandBufferBuilder { self.validate_push_constants(&pipeline_layout, offset, &push_constants)?; - unsafe { Ok(self.push_constants_unchecked(pipeline_layout, offset, push_constants)) } + Ok(unsafe { self.push_constants_unchecked(pipeline_layout, offset, push_constants) }) } fn validate_push_constants( @@ -505,14 +505,14 @@ impl AutoCommandBufferBuilder { &descriptor_writes, )?; - unsafe { - Ok(self.push_descriptor_set_unchecked( + Ok(unsafe { + self.push_descriptor_set_unchecked( pipeline_bind_point, pipeline_layout, set_num, descriptor_writes, - )) - } + ) + }) } fn validate_push_descriptor_set( diff --git a/vulkano/src/command_buffer/commands/clear.rs b/vulkano/src/command_buffer/commands/clear.rs index d55126bc..9dde8c58 100644 --- a/vulkano/src/command_buffer/commands/clear.rs +++ b/vulkano/src/command_buffer/commands/clear.rs @@ -22,7 +22,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_clear_color_image(&clear_info)?; - unsafe { Ok(self.clear_color_image_unchecked(clear_info)) } + Ok(unsafe { self.clear_color_image_unchecked(clear_info) }) } fn validate_clear_color_image( @@ -88,7 +88,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_clear_depth_stencil_image(&clear_info)?; - unsafe { Ok(self.clear_depth_stencil_image_unchecked(clear_info)) } + Ok(unsafe { self.clear_depth_stencil_image_unchecked(clear_info) }) } fn validate_clear_depth_stencil_image( @@ -158,7 +158,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_fill_buffer(&dst_buffer, data)?; - unsafe { Ok(self.fill_buffer_unchecked(dst_buffer, data)) } + Ok(unsafe { self.fill_buffer_unchecked(dst_buffer, data) }) } fn validate_fill_buffer( @@ -220,7 +220,7 @@ impl AutoCommandBufferBuilder { size_of_val(data.deref()) as DeviceSize, )?; - unsafe { Ok(self.update_buffer_unchecked(dst_buffer, data)) } + Ok(unsafe { self.update_buffer_unchecked(dst_buffer, data) }) } fn validate_update_buffer( diff --git a/vulkano/src/command_buffer/commands/copy.rs b/vulkano/src/command_buffer/commands/copy.rs index a2c2262f..35eb462e 100644 --- a/vulkano/src/command_buffer/commands/copy.rs +++ b/vulkano/src/command_buffer/commands/copy.rs @@ -33,7 +33,7 @@ impl AutoCommandBufferBuilder { let copy_buffer_info = copy_buffer_info.into(); self.validate_copy_buffer(©_buffer_info)?; - unsafe { Ok(self.copy_buffer_unchecked(copy_buffer_info)) } + Ok(unsafe { self.copy_buffer_unchecked(copy_buffer_info) }) } fn validate_copy_buffer( @@ -131,7 +131,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_copy_image(©_image_info)?; - unsafe { Ok(self.copy_image_unchecked(copy_image_info)) } + Ok(unsafe { self.copy_image_unchecked(copy_image_info) }) } fn validate_copy_image( @@ -215,7 +215,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_copy_buffer_to_image(©_buffer_to_image_info)?; - unsafe { Ok(self.copy_buffer_to_image_unchecked(copy_buffer_to_image_info)) } + Ok(unsafe { self.copy_buffer_to_image_unchecked(copy_buffer_to_image_info) }) } fn validate_copy_buffer_to_image( @@ -302,7 +302,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_copy_image_to_buffer(©_image_to_buffer_info)?; - unsafe { Ok(self.copy_image_to_buffer_unchecked(copy_image_to_buffer_info)) } + Ok(unsafe { self.copy_image_to_buffer_unchecked(copy_image_to_buffer_info) }) } fn validate_copy_image_to_buffer( @@ -418,7 +418,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_blit_image(&blit_image_info)?; - unsafe { Ok(self.blit_image_unchecked(blit_image_info)) } + Ok(unsafe { self.blit_image_unchecked(blit_image_info) }) } fn validate_blit_image( @@ -506,7 +506,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_resolve_image(&resolve_image_info)?; - unsafe { Ok(self.resolve_image_unchecked(resolve_image_info)) } + Ok(unsafe { self.resolve_image_unchecked(resolve_image_info) }) } fn validate_resolve_image( diff --git a/vulkano/src/command_buffer/commands/debug.rs b/vulkano/src/command_buffer/commands/debug.rs index e86e4c5e..e0de7b40 100644 --- a/vulkano/src/command_buffer/commands/debug.rs +++ b/vulkano/src/command_buffer/commands/debug.rs @@ -18,7 +18,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_begin_debug_utils_label(&label_info)?; - unsafe { Ok(self.begin_debug_utils_label_unchecked(label_info)) } + Ok(unsafe { self.begin_debug_utils_label_unchecked(label_info) }) } fn validate_begin_debug_utils_label( @@ -89,7 +89,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_insert_debug_utils_label(&label_info)?; - unsafe { Ok(self.insert_debug_utils_label_unchecked(label_info)) } + Ok(unsafe { self.insert_debug_utils_label_unchecked(label_info) }) } fn validate_insert_debug_utils_label( diff --git a/vulkano/src/command_buffer/commands/dynamic_state.rs b/vulkano/src/command_buffer/commands/dynamic_state.rs index 56465eac..8e9a8a08 100644 --- a/vulkano/src/command_buffer/commands/dynamic_state.rs +++ b/vulkano/src/command_buffer/commands/dynamic_state.rs @@ -54,7 +54,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_blend_constants(constants)?; - unsafe { Ok(self.set_blend_constants_unchecked(constants)) } + Ok(unsafe { self.set_blend_constants_unchecked(constants) }) } fn validate_set_blend_constants( @@ -90,7 +90,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_color_write_enable(&enables)?; - unsafe { Ok(self.set_color_write_enable_unchecked(enables)) } + Ok(unsafe { self.set_color_write_enable_unchecked(enables) }) } fn validate_set_color_write_enable( @@ -146,7 +146,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_cull_mode(cull_mode)?; - unsafe { Ok(self.set_cull_mode_unchecked(cull_mode)) } + Ok(unsafe { self.set_cull_mode_unchecked(cull_mode) }) } fn validate_set_cull_mode(&self, cull_mode: CullMode) -> Result<(), Box> { @@ -180,7 +180,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_depth_bias(constant_factor, clamp, slope_factor)?; - unsafe { Ok(self.set_depth_bias_unchecked(constant_factor, clamp, slope_factor)) } + Ok(unsafe { self.set_depth_bias_unchecked(constant_factor, clamp, slope_factor) }) } fn validate_set_depth_bias( @@ -227,7 +227,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_depth_bias_enable(enable)?; - unsafe { Ok(self.set_depth_bias_enable_unchecked(enable)) } + Ok(unsafe { self.set_depth_bias_enable_unchecked(enable) }) } fn validate_set_depth_bias_enable(&self, enable: bool) -> Result<(), Box> { @@ -259,7 +259,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_depth_bounds(bounds.clone())?; - unsafe { Ok(self.set_depth_bounds_unchecked(bounds)) } + Ok(unsafe { self.set_depth_bounds_unchecked(bounds) }) } fn validate_set_depth_bounds( @@ -294,7 +294,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_depth_bounds_test_enable(enable)?; - unsafe { Ok(self.set_depth_bounds_test_enable_unchecked(enable)) } + Ok(unsafe { self.set_depth_bounds_test_enable_unchecked(enable) }) } fn validate_set_depth_bounds_test_enable( @@ -329,7 +329,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_depth_compare_op(compare_op)?; - unsafe { Ok(self.set_depth_compare_op_unchecked(compare_op)) } + Ok(unsafe { self.set_depth_compare_op_unchecked(compare_op) }) } fn validate_set_depth_compare_op( @@ -364,7 +364,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_depth_test_enable(enable)?; - unsafe { Ok(self.set_depth_test_enable_unchecked(enable)) } + Ok(unsafe { self.set_depth_test_enable_unchecked(enable) }) } fn validate_set_depth_test_enable(&self, enable: bool) -> Result<(), Box> { @@ -396,7 +396,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_depth_write_enable(enable)?; - unsafe { Ok(self.set_depth_write_enable_unchecked(enable)) } + Ok(unsafe { self.set_depth_write_enable_unchecked(enable) }) } fn validate_set_depth_write_enable(&self, enable: bool) -> Result<(), Box> { @@ -429,7 +429,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_discard_rectangle(first_rectangle, &rectangles)?; - unsafe { Ok(self.set_discard_rectangle_unchecked(first_rectangle, rectangles)) } + Ok(unsafe { self.set_discard_rectangle_unchecked(first_rectangle, rectangles) }) } fn validate_set_discard_rectangle( @@ -471,7 +471,7 @@ impl AutoCommandBufferBuilder { pub fn set_front_face(&mut self, face: FrontFace) -> Result<&mut Self, Box> { self.validate_set_front_face(face)?; - unsafe { Ok(self.set_front_face_unchecked(face)) } + Ok(unsafe { self.set_front_face_unchecked(face) }) } fn validate_set_front_face(&self, face: FrontFace) -> Result<(), Box> { @@ -504,7 +504,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_line_stipple(factor, pattern)?; - unsafe { Ok(self.set_line_stipple_unchecked(factor, pattern)) } + Ok(unsafe { self.set_line_stipple_unchecked(factor, pattern) }) } fn validate_set_line_stipple( @@ -537,7 +537,7 @@ impl AutoCommandBufferBuilder { pub fn set_line_width(&mut self, line_width: f32) -> Result<&mut Self, Box> { self.validate_set_line_width(line_width)?; - unsafe { Ok(self.set_line_width_unchecked(line_width)) } + Ok(unsafe { self.set_line_width_unchecked(line_width) }) } fn validate_set_line_width(&self, line_width: f32) -> Result<(), Box> { @@ -566,7 +566,7 @@ impl AutoCommandBufferBuilder { pub fn set_logic_op(&mut self, logic_op: LogicOp) -> Result<&mut Self, Box> { self.validate_set_logic_op(logic_op)?; - unsafe { Ok(self.set_logic_op_unchecked(logic_op)) } + Ok(unsafe { self.set_logic_op_unchecked(logic_op) }) } fn validate_set_logic_op(&self, logic_op: LogicOp) -> Result<(), Box> { @@ -598,7 +598,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_patch_control_points(num)?; - unsafe { Ok(self.set_patch_control_points_unchecked(num)) } + Ok(unsafe { self.set_patch_control_points_unchecked(num) }) } fn validate_set_patch_control_points(&self, num: u32) -> Result<(), Box> { @@ -630,7 +630,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_primitive_restart_enable(enable)?; - unsafe { Ok(self.set_primitive_restart_enable_unchecked(enable)) } + Ok(unsafe { self.set_primitive_restart_enable_unchecked(enable) }) } fn validate_set_primitive_restart_enable( @@ -665,7 +665,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_primitive_topology(topology)?; - unsafe { Ok(self.set_primitive_topology_unchecked(topology)) } + Ok(unsafe { self.set_primitive_topology_unchecked(topology) }) } fn validate_set_primitive_topology( @@ -703,7 +703,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_rasterizer_discard_enable(enable)?; - unsafe { Ok(self.set_rasterizer_discard_enable_unchecked(enable)) } + Ok(unsafe { self.set_rasterizer_discard_enable_unchecked(enable) }) } fn validate_set_rasterizer_discard_enable( @@ -739,7 +739,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_scissor(first_scissor, &scissors)?; - unsafe { Ok(self.set_scissor_unchecked(first_scissor, scissors)) } + Ok(unsafe { self.set_scissor_unchecked(first_scissor, scissors) }) } fn validate_set_scissor( @@ -785,7 +785,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_scissor_with_count(&scissors)?; - unsafe { Ok(self.set_scissor_with_count_unchecked(scissors)) } + Ok(unsafe { self.set_scissor_with_count_unchecked(scissors) }) } fn validate_set_scissor_with_count( @@ -824,7 +824,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_stencil_compare_mask(faces, compare_mask)?; - unsafe { Ok(self.set_stencil_compare_mask_unchecked(faces, compare_mask)) } + Ok(unsafe { self.set_stencil_compare_mask_unchecked(faces, compare_mask) }) } fn validate_set_stencil_compare_mask( @@ -878,9 +878,9 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_stencil_op(faces, fail_op, pass_op, depth_fail_op, compare_op)?; - unsafe { - Ok(self.set_stencil_op_unchecked(faces, fail_op, pass_op, depth_fail_op, compare_op)) - } + Ok(unsafe { + self.set_stencil_op_unchecked(faces, fail_op, pass_op, depth_fail_op, compare_op) + }) } fn validate_set_stencil_op( @@ -947,7 +947,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_stencil_reference(faces, reference)?; - unsafe { Ok(self.set_stencil_reference_unchecked(faces, reference)) } + Ok(unsafe { self.set_stencil_reference_unchecked(faces, reference) }) } fn validate_set_stencil_reference( @@ -997,7 +997,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_stencil_test_enable(enable)?; - unsafe { Ok(self.set_stencil_test_enable_unchecked(enable)) } + Ok(unsafe { self.set_stencil_test_enable_unchecked(enable) }) } fn validate_set_stencil_test_enable(&self, enable: bool) -> Result<(), Box> { @@ -1030,7 +1030,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_stencil_write_mask(faces, write_mask)?; - unsafe { Ok(self.set_stencil_write_mask_unchecked(faces, write_mask)) } + Ok(unsafe { self.set_stencil_write_mask_unchecked(faces, write_mask) }) } fn validate_set_stencil_write_mask( @@ -1081,7 +1081,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_vertex_input(&vertex_input_state)?; - unsafe { Ok(self.set_vertex_input_unchecked(vertex_input_state)) } + Ok(unsafe { self.set_vertex_input_unchecked(vertex_input_state) }) } fn validate_set_vertex_input( @@ -1121,7 +1121,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_viewport(first_viewport, &viewports)?; - unsafe { Ok(self.set_viewport_unchecked(first_viewport, viewports)) } + Ok(unsafe { self.set_viewport_unchecked(first_viewport, viewports) }) } fn validate_set_viewport( @@ -1166,7 +1166,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_viewport_with_count(&viewports)?; - unsafe { Ok(self.set_viewport_with_count_unchecked(viewports)) } + Ok(unsafe { self.set_viewport_with_count_unchecked(viewports) }) } fn validate_set_viewport_with_count( @@ -1205,9 +1205,9 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_conservative_rasterization_mode()?; - unsafe { - Ok(self.set_conservative_rasterization_mode_unchecked(conservative_rasterization_mode)) - } + Ok(unsafe { + self.set_conservative_rasterization_mode_unchecked(conservative_rasterization_mode) + }) } fn validate_set_conservative_rasterization_mode(&self) -> Result<(), Box> { @@ -1244,11 +1244,11 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_extra_primitive_overestimation_size()?; - unsafe { - Ok(self.set_extra_primitive_overestimation_size_unchecked( + Ok(unsafe { + self.set_extra_primitive_overestimation_size_unchecked( extra_primitive_overestimation_size, - )) - } + ) + }) } fn validate_set_extra_primitive_overestimation_size(&self) -> Result<(), Box> { @@ -1291,7 +1291,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_set_fragment_shading_rate(fragment_size, combiner_ops)?; - unsafe { Ok(self.set_fragment_shading_rate_unchecked(fragment_size, combiner_ops)) } + Ok(unsafe { self.set_fragment_shading_rate_unchecked(fragment_size, combiner_ops) }) } fn validate_set_fragment_shading_rate( diff --git a/vulkano/src/command_buffer/commands/pipeline.rs b/vulkano/src/command_buffer/commands/pipeline.rs index 9cc392a4..e85bd486 100644 --- a/vulkano/src/command_buffer/commands/pipeline.rs +++ b/vulkano/src/command_buffer/commands/pipeline.rs @@ -68,7 +68,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_dispatch(group_counts)?; - unsafe { Ok(self.dispatch_unchecked(group_counts)) } + Ok(unsafe { self.dispatch_unchecked(group_counts) }) } fn validate_dispatch(&self, group_counts: [u32; 3]) -> Result<(), Box> { @@ -143,7 +143,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_dispatch_indirect(indirect_buffer.as_bytes())?; - unsafe { Ok(self.dispatch_indirect_unchecked(indirect_buffer)) } + Ok(unsafe { self.dispatch_indirect_unchecked(indirect_buffer) }) } fn validate_dispatch_indirect( @@ -231,9 +231,9 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_draw(vertex_count, instance_count, first_vertex, first_instance)?; - unsafe { - Ok(self.draw_unchecked(vertex_count, instance_count, first_vertex, first_instance)) - } + Ok(unsafe { + self.draw_unchecked(vertex_count, instance_count, first_vertex, first_instance) + }) } fn validate_draw( @@ -422,7 +422,7 @@ impl AutoCommandBufferBuilder { let stride = size_of::() as u32; self.validate_draw_indirect(indirect_buffer.as_bytes(), draw_count, stride)?; - unsafe { Ok(self.draw_indirect_unchecked(indirect_buffer, draw_count, stride)) } + Ok(unsafe { self.draw_indirect_unchecked(indirect_buffer, draw_count, stride) }) } fn validate_draw_indirect( @@ -538,14 +538,14 @@ impl AutoCommandBufferBuilder { stride, )?; - unsafe { - Ok(self.draw_indirect_count_unchecked( + Ok(unsafe { + self.draw_indirect_count_unchecked( indirect_buffer, count_buffer, max_draw_count, stride, - )) - } + ) + }) } fn validate_draw_indirect_count( @@ -681,15 +681,15 @@ impl AutoCommandBufferBuilder { first_instance, )?; - unsafe { - Ok(self.draw_indexed_unchecked( + Ok(unsafe { + self.draw_indexed_unchecked( index_count, instance_count, first_index, vertex_offset, first_instance, - )) - } + ) + }) } fn validate_draw_indexed( @@ -909,7 +909,7 @@ impl AutoCommandBufferBuilder { let stride = size_of::() as u32; self.validate_draw_indexed_indirect(indirect_buffer.as_bytes(), draw_count, stride)?; - unsafe { Ok(self.draw_indexed_indirect_unchecked(indirect_buffer, draw_count, stride)) } + Ok(unsafe { self.draw_indexed_indirect_unchecked(indirect_buffer, draw_count, stride) }) } fn validate_draw_indexed_indirect( @@ -1040,14 +1040,14 @@ impl AutoCommandBufferBuilder { stride, )?; - unsafe { - Ok(self.draw_indexed_indirect_count_unchecked( + Ok(unsafe { + self.draw_indexed_indirect_count_unchecked( indirect_buffer, count_buffer, max_draw_count, stride, - )) - } + ) + }) } fn validate_draw_indexed_indirect_count( @@ -1163,7 +1163,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_draw_mesh_tasks(group_counts)?; - unsafe { Ok(self.draw_mesh_tasks_unchecked(group_counts)) } + Ok(unsafe { self.draw_mesh_tasks_unchecked(group_counts) }) } fn validate_draw_mesh_tasks(&self, group_counts: [u32; 3]) -> Result<(), Box> { @@ -1361,7 +1361,7 @@ impl AutoCommandBufferBuilder { let stride = size_of::() as u32; self.validate_draw_mesh_tasks_indirect(indirect_buffer.as_bytes(), draw_count, stride)?; - unsafe { Ok(self.draw_mesh_tasks_indirect_unchecked(indirect_buffer, draw_count, stride)) } + Ok(unsafe { self.draw_mesh_tasks_indirect_unchecked(indirect_buffer, draw_count, stride) }) } fn validate_draw_mesh_tasks_indirect( @@ -1485,14 +1485,14 @@ impl AutoCommandBufferBuilder { stride, )?; - unsafe { - Ok(self.draw_mesh_tasks_indirect_count_unchecked( + Ok(unsafe { + self.draw_mesh_tasks_indirect_count_unchecked( indirect_buffer, count_buffer, max_draw_count, stride, - )) - } + ) + }) } fn validate_draw_mesh_tasks_indirect_count( diff --git a/vulkano/src/command_buffer/commands/query.rs b/vulkano/src/command_buffer/commands/query.rs index e2c80ea2..e9a1ec1d 100644 --- a/vulkano/src/command_buffer/commands/query.rs +++ b/vulkano/src/command_buffer/commands/query.rs @@ -113,7 +113,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_end_query(&query_pool, query)?; - unsafe { Ok(self.end_query_unchecked(query_pool, query)) } + Ok(unsafe { self.end_query_unchecked(query_pool, query) }) } fn validate_end_query( @@ -265,9 +265,9 @@ impl AutoCommandBufferBuilder { { self.validate_copy_query_pool_results(&query_pool, queries.clone(), &destination, flags)?; - unsafe { - Ok(self.copy_query_pool_results_unchecked(query_pool, queries, destination, flags)) - } + Ok(unsafe { + self.copy_query_pool_results_unchecked(query_pool, queries, destination, flags) + }) } fn validate_copy_query_pool_results( diff --git a/vulkano/src/command_buffer/commands/render_pass.rs b/vulkano/src/command_buffer/commands/render_pass.rs index 1235a8d6..ad560ec6 100644 --- a/vulkano/src/command_buffer/commands/render_pass.rs +++ b/vulkano/src/command_buffer/commands/render_pass.rs @@ -38,7 +38,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_begin_render_pass(&render_pass_begin_info, &subpass_begin_info)?; - unsafe { Ok(self.begin_render_pass_unchecked(render_pass_begin_info, subpass_begin_info)) } + Ok(unsafe { self.begin_render_pass_unchecked(render_pass_begin_info, subpass_begin_info) }) } fn validate_begin_render_pass( @@ -154,7 +154,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_next_subpass(&subpass_end_info, &subpass_begin_info)?; - unsafe { Ok(self.next_subpass_unchecked(subpass_end_info, subpass_begin_info)) } + Ok(unsafe { self.next_subpass_unchecked(subpass_end_info, subpass_begin_info) }) } fn validate_next_subpass( @@ -257,7 +257,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_end_render_pass(&subpass_end_info)?; - unsafe { Ok(self.end_render_pass_unchecked(subpass_end_info)) } + Ok(unsafe { self.end_render_pass_unchecked(subpass_end_info) }) } fn validate_end_render_pass( @@ -343,7 +343,7 @@ impl AutoCommandBufferBuilder { rendering_info.set_auto_extent_layers(); self.validate_begin_rendering(&rendering_info)?; - unsafe { Ok(self.begin_rendering_unchecked(rendering_info)) } + Ok(unsafe { self.begin_rendering_unchecked(rendering_info) }) } fn validate_begin_rendering( @@ -573,7 +573,7 @@ impl AutoCommandBufferBuilder { pub fn end_rendering(&mut self) -> Result<&mut Self, Box> { self.validate_end_rendering()?; - unsafe { Ok(self.end_rendering_unchecked()) } + Ok(unsafe { self.end_rendering_unchecked() }) } fn validate_end_rendering(&self) -> Result<(), Box> { @@ -656,7 +656,7 @@ impl AutoCommandBufferBuilder { ) -> Result<&mut Self, Box> { self.validate_clear_attachments(&attachments, &rects)?; - unsafe { Ok(self.clear_attachments_unchecked(attachments, rects)) } + Ok(unsafe { self.clear_attachments_unchecked(attachments, rects) }) } fn validate_clear_attachments( diff --git a/vulkano/src/command_buffer/commands/secondary.rs b/vulkano/src/command_buffer/commands/secondary.rs index b33b9887..500a43b7 100644 --- a/vulkano/src/command_buffer/commands/secondary.rs +++ b/vulkano/src/command_buffer/commands/secondary.rs @@ -30,7 +30,7 @@ impl AutoCommandBufferBuilder { let command_buffer = DropUnlockCommandBuffer::new(command_buffer)?; self.validate_execute_commands(iter::once(&**command_buffer))?; - unsafe { Ok(self.execute_commands_locked(smallvec![command_buffer])) } + Ok(unsafe { self.execute_commands_locked(smallvec![command_buffer]) }) } /// Executes multiple secondary command buffers in a vector. @@ -50,7 +50,7 @@ impl AutoCommandBufferBuilder { self.validate_execute_commands(command_buffers.iter().map(|cb| &***cb))?; - unsafe { Ok(self.execute_commands_locked(command_buffers)) } + Ok(unsafe { self.execute_commands_locked(command_buffers) }) } fn validate_execute_commands<'a>( diff --git a/vulkano/src/command_buffer/mod.rs b/vulkano/src/command_buffer/mod.rs index deaae82f..0dfd48bd 100644 --- a/vulkano/src/command_buffer/mod.rs +++ b/vulkano/src/command_buffer/mod.rs @@ -74,10 +74,7 @@ //! .unwrap() //! .bind_vertex_buffers(0, vertex_buffer.clone()) //! .unwrap(); -//! -//! unsafe { -//! cb.draw(vertex_buffer.len() as u32, 1, 0, 0).unwrap(); -//! } +//! unsafe { cb.draw(vertex_buffer.len() as u32, 1, 0, 0) }.unwrap(); //! //! cb.end_render_pass(Default::default()).unwrap(); //! @@ -704,12 +701,9 @@ impl CommandBufferInheritanceRenderingInfo { })); } - let potential_format_features = unsafe { - device - .physical_device() - .format_properties_unchecked(format) - .potential_format_features() - }; + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + let potential_format_features = format_properties.potential_format_features(); if !potential_format_features.intersects(FormatFeatures::COLOR_ATTACHMENT) { return Err(Box::new(ValidationError { @@ -748,12 +742,9 @@ impl CommandBufferInheritanceRenderingInfo { })); } - let potential_format_features = unsafe { - device - .physical_device() - .format_properties_unchecked(format) - .potential_format_features() - }; + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + let potential_format_features = format_properties.potential_format_features(); if !potential_format_features.intersects(FormatFeatures::DEPTH_STENCIL_ATTACHMENT) { return Err(Box::new(ValidationError { @@ -793,12 +784,9 @@ impl CommandBufferInheritanceRenderingInfo { })); } - let potential_format_features = unsafe { - device - .physical_device() - .format_properties_unchecked(format) - .potential_format_features() - }; + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + let potential_format_features = format_properties.potential_format_features(); if !potential_format_features.intersects(FormatFeatures::DEPTH_STENCIL_ATTACHMENT) { return Err(Box::new(ValidationError { diff --git a/vulkano/src/command_buffer/pool.rs b/vulkano/src/command_buffer/pool.rs index e9cba01c..fcd7cb1d 100644 --- a/vulkano/src/command_buffer/pool.rs +++ b/vulkano/src/command_buffer/pool.rs @@ -45,7 +45,7 @@ impl CommandPool { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -175,19 +175,21 @@ impl CommandPool { let allocate_info_vk = allocate_info.to_vk(self.handle); let command_buffer_count = command_buffer_count as usize; + let fns = self.device.fns(); + let mut out = Vec::with_capacity(command_buffer_count); + unsafe { - let fns = self.device.fns(); - let mut out = Vec::with_capacity(command_buffer_count); (fns.v1_0.allocate_command_buffers)( self.device.handle(), &allocate_info_vk, out.as_mut_ptr(), ) - .result() - .map_err(VulkanError::from)?; - out.set_len(command_buffer_count); - out } + .result() + .map_err(VulkanError::from)?; + unsafe { out.set_len(command_buffer_count) }; + + out }; let device = self.device.clone(); @@ -302,10 +304,8 @@ impl CommandPool { impl Drop for CommandPool { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_command_pool)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_command_pool)(self.device.handle(), self.handle, ptr::null()) }; } } diff --git a/vulkano/src/command_buffer/traits.rs b/vulkano/src/command_buffer/traits.rs index 6f7c1fc0..63432233 100644 --- a/vulkano/src/command_buffer/traits.rs +++ b/vulkano/src/command_buffer/traits.rs @@ -203,24 +203,23 @@ where } fn flush(&self) -> Result<(), Validated> { - unsafe { - let mut submitted = self.submitted.lock(); - if *submitted { - return Ok(()); - } + let mut submitted = self.submitted.lock(); - match self.build_submission_impl()? { - SubmitAnyBuilder::Empty => {} - SubmitAnyBuilder::CommandBuffer(submit_info, fence) => { - queue_submit(&self.queue, submit_info, fence, &self.previous).unwrap(); - } - _ => unreachable!(), - }; - - // Only write `true` here in order to try again next time if we failed to submit. - *submitted = true; - Ok(()) + if *submitted { + return Ok(()); } + + match unsafe { self.build_submission_impl() }? { + SubmitAnyBuilder::Empty => {} + SubmitAnyBuilder::CommandBuffer(submit_info, fence) => { + unsafe { queue_submit(&self.queue, submit_info, fence, &self.previous) }.unwrap(); + } + _ => unreachable!(), + }; + + // Only write `true` here in order to try again next time if we failed to submit. + *submitted = true; + Ok(()) } unsafe fn signal_finished(&self) { diff --git a/vulkano/src/deferred.rs b/vulkano/src/deferred.rs index f48b2257..8804276b 100644 --- a/vulkano/src/deferred.rs +++ b/vulkano/src/deferred.rs @@ -34,7 +34,7 @@ impl DeferredOperation { pub fn new(device: Arc) -> Result, Validated> { Self::validate_new(&device)?; - unsafe { Ok(Self::new_unchecked(device)?) } + Ok(unsafe { Self::new_unchecked(device) }?) } fn validate_new(device: &Device) -> Result<(), Box> { @@ -85,8 +85,8 @@ impl DeferredOperation { /// Executes a portion of the operation on the current thread. pub fn join(&self) -> Result { + let fns = self.device.fns(); let result = unsafe { - let fns = self.device.fns(); (fns.khr_deferred_host_operations.deferred_operation_join_khr)( self.device.handle(), self.handle, @@ -103,8 +103,8 @@ impl DeferredOperation { /// Returns the result of the operation, or `None` if the operation is not yet complete. pub fn result(&self) -> Option> { + let fns = self.device.fns(); let result = unsafe { - let fns = self.device.fns(); (fns.khr_deferred_host_operations .get_deferred_operation_result_khr)(self.device.handle(), self.handle) }; @@ -149,8 +149,8 @@ impl DeferredOperation { /// /// Returns `None` if no exact number of threads can be calculated. pub fn max_concurrency(&self) -> Option { + let fns = self.device.fns(); let result = unsafe { - let fns = self.device.fns(); (fns.khr_deferred_host_operations .get_deferred_operation_max_concurrency_khr)( self.device.handle(), self.handle @@ -166,13 +166,13 @@ impl Drop for DeferredOperation { fn drop(&mut self) { let _ = self.wait(); // Ignore errors + let fns = self.device.fns(); unsafe { - let fns = self.device.fns(); (fns.khr_deferred_host_operations .destroy_deferred_operation_khr)( self.device.handle(), self.handle, ptr::null() - ); - } + ) + }; } } diff --git a/vulkano/src/descriptor_set/allocator.rs b/vulkano/src/descriptor_set/allocator.rs index 872e21ad..4844dbf2 100644 --- a/vulkano/src/descriptor_set/allocator.rs +++ b/vulkano/src/descriptor_set/allocator.rs @@ -211,7 +211,8 @@ impl StandardDescriptorSetAllocator { /// This has no effect if the entry was not initialized yet. #[inline] pub fn clear(&self, layout: &Arc) { - unsafe { &mut *self.pools.get_or(Default::default).get() }.remove(layout.id()) + let entry_ptr = self.pools.get_or(Default::default).get(); + unsafe { &mut *entry_ptr }.remove(layout.id()) } /// Clears all entries for the current thread. This does not mean that the pools are dropped @@ -220,7 +221,8 @@ impl StandardDescriptorSetAllocator { /// This has no effect if no entries were initialized yet. #[inline] pub fn clear_all(&self) { - unsafe { *self.pools.get_or(Default::default).get() = SortedMap::default() }; + let entry_ptr = self.pools.get_or(Default::default).get(); + unsafe { *entry_ptr = SortedMap::default() }; } } @@ -234,7 +236,8 @@ unsafe impl DescriptorSetAllocator for StandardDescriptorSetAllocator { let is_fixed = layout.variable_descriptor_count() == 0; let pools = self.pools.get_or_default(); - let entry = unsafe { &mut *pools.get() }.get_or_try_insert(layout.id(), || { + let entry_ptr = pools.get(); + let entry = unsafe { &mut *entry_ptr }.get_or_try_insert(layout.id(), || { if is_fixed { FixedEntry::new(layout, &self.create_info).map(Entry::Fixed) } else { diff --git a/vulkano/src/descriptor_set/layout.rs b/vulkano/src/descriptor_set/layout.rs index 3445ae9d..13a97486 100644 --- a/vulkano/src/descriptor_set/layout.rs +++ b/vulkano/src/descriptor_set/layout.rs @@ -37,7 +37,7 @@ impl DescriptorSetLayout { ) -> Result, Validated> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -63,11 +63,7 @@ impl DescriptorSetLayout { // Safety: create_info is validated, and we only enter here if the // max_per_set_descriptors property exists (which means this function exists too). if total_descriptor_count > max_per_set_descriptors - && unsafe { - device - .descriptor_set_layout_support_unchecked(create_info) - .is_none() - } + && unsafe { device.descriptor_set_layout_support_unchecked(create_info) }.is_none() { return Err(Box::new(ValidationError { problem: "the total number of descriptors across all bindings is greater than \ @@ -201,14 +197,10 @@ impl DescriptorSetLayout { impl Drop for DescriptorSetLayout { #[inline] fn drop(&mut self) { + let fns = self.device.fns(); unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_descriptor_set_layout)( - self.device.handle(), - self.handle, - ptr::null(), - ); - } + (fns.v1_0.destroy_descriptor_set_layout)(self.device.handle(), self.handle, ptr::null()) + }; } } diff --git a/vulkano/src/descriptor_set/mod.rs b/vulkano/src/descriptor_set/mod.rs index f220fc79..f1c886f0 100644 --- a/vulkano/src/descriptor_set/mod.rs +++ b/vulkano/src/descriptor_set/mod.rs @@ -209,8 +209,8 @@ impl DescriptorSet { self.resources.get_mut(), &descriptor_writes, &descriptor_copies, - ); - } + ) + }; Ok(()) } diff --git a/vulkano/src/descriptor_set/pool.rs b/vulkano/src/descriptor_set/pool.rs index e9b0f0e2..3d06ef18 100644 --- a/vulkano/src/descriptor_set/pool.rs +++ b/vulkano/src/descriptor_set/pool.rs @@ -41,7 +41,7 @@ impl DescriptorPool { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -66,21 +66,23 @@ impl DescriptorPool { let create_info_vk = create_info.to_vk(&create_info_fields1_vk, &mut create_info_extensions_vk); - let handle = unsafe { + let handle = { let fns = device.fns(); let mut output = MaybeUninit::uninit(); - (fns.v1_0.create_descriptor_pool)( - device.handle(), - &create_info_vk, - ptr::null(), - output.as_mut_ptr(), - ) + unsafe { + (fns.v1_0.create_descriptor_pool)( + device.handle(), + &create_info_vk, + ptr::null(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; - unsafe { Ok(Self::from_handle(device, handle, create_info)) } + Ok(unsafe { Self::from_handle(device, handle, create_info) }) } /// Creates a new `DescriptorPool` from a raw object handle. @@ -374,10 +376,10 @@ impl DescriptorPool { impl Drop for DescriptorPool { #[inline] fn drop(&mut self) { + let fns = self.device.fns(); unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_descriptor_pool)(self.device.handle(), self.handle, ptr::null()); - } + (fns.v1_0.destroy_descriptor_pool)(self.device.handle(), self.handle, ptr::null()) + }; } } @@ -812,12 +814,10 @@ mod tests { }, ) .unwrap(); - unsafe { - let sets = pool - .allocate_descriptor_sets([DescriptorSetAllocateInfo::new(set_layout)]) + let sets = + unsafe { pool.allocate_descriptor_sets([DescriptorSetAllocateInfo::new(set_layout)]) } .unwrap(); - assert_eq!(sets.count(), 1); - } + assert_eq!(sets.count(), 1); } #[test] @@ -852,9 +852,9 @@ mod tests { ) .unwrap(); - unsafe { - let _ = pool.allocate_descriptor_sets([DescriptorSetAllocateInfo::new(set_layout)]); - } + let _ = unsafe { + pool.allocate_descriptor_sets([DescriptorSetAllocateInfo::new(set_layout)]) + }; }); } @@ -871,9 +871,7 @@ mod tests { }, ) .unwrap(); - unsafe { - let sets = pool.allocate_descriptor_sets([]).unwrap(); - assert_eq!(sets.count(), 0); - } + let sets = unsafe { pool.allocate_descriptor_sets([]) }.unwrap(); + assert_eq!(sets.count(), 0); } } diff --git a/vulkano/src/device/mod.rs b/vulkano/src/device/mod.rs index 89253e2f..62f8f400 100644 --- a/vulkano/src/device/mod.rs +++ b/vulkano/src/device/mod.rs @@ -179,7 +179,7 @@ impl Device { { Self::validate_new(&physical_device, &create_info)?; - unsafe { Ok(Self::new_unchecked(physical_device, create_info)?) } + Ok(unsafe { Self::new_unchecked(physical_device, create_info) }?) } fn validate_new( @@ -363,19 +363,20 @@ impl Device { let create_info_vk = create_info.to_vk(&create_info_fields1_vk, &mut create_info_extensions); + let fns = physical_device.instance().fns(); + + let mut output = MaybeUninit::uninit(); unsafe { - let fns = physical_device.instance().fns(); - let mut output = MaybeUninit::uninit(); (fns.v1_0.create_device)( physical_device.handle(), &create_info_vk, ptr::null(), output.as_mut_ptr(), ) - .result() - .map_err(VulkanError::from)?; - output.assume_init() } + .result() + .map_err(VulkanError::from)?; + unsafe { output.assume_init() } }; Ok(Self::from_handle(physical_device, handle, create_info)) @@ -402,9 +403,11 @@ impl Device { } = create_info; let api_version = physical_device.api_version(); - let fns = DeviceFunctions::load(|name| unsafe { - (physical_device.instance().fns().v1_0.get_device_proc_addr)(handle, name.as_ptr()) - .map_or(ptr::null(), |func| func as _) + let fns = DeviceFunctions::load(|name| { + unsafe { + (physical_device.instance().fns().v1_0.get_device_proc_addr)(handle, name.as_ptr()) + } + .map_or(ptr::null(), |func| func as _) }); let mut active_queue_family_indices: SmallVec<[_; 2]> = @@ -577,13 +580,13 @@ impl Device { max_primitive_counts, )?; - unsafe { - Ok(self.acceleration_structure_build_sizes_unchecked( + Ok(unsafe { + self.acceleration_structure_build_sizes_unchecked( build_type, build_info, max_primitive_counts, - )) - } + ) + }) } fn validate_acceleration_structure_build_sizes( @@ -728,7 +731,7 @@ impl Device { ) -> Result> { self.validate_acceleration_structure_is_compatible(version_data)?; - unsafe { Ok(self.acceleration_structure_is_compatible_unchecked(version_data)) } + Ok(unsafe { self.acceleration_structure_is_compatible_unchecked(version_data) }) } fn validate_acceleration_structure_is_compatible( @@ -797,7 +800,7 @@ impl Device { ) -> Result, Box> { self.validate_descriptor_set_layout_support(create_info)?; - unsafe { Ok(self.descriptor_set_layout_support_unchecked(create_info)) } + Ok(unsafe { self.descriptor_set_layout_support_unchecked(create_info) }) } fn validate_descriptor_set_layout_support( @@ -875,7 +878,7 @@ impl Device { ) -> Result> { self.validate_buffer_memory_requirements(&create_info)?; - unsafe { Ok(self.buffer_memory_requirements_unchecked(create_info)) } + Ok(unsafe { self.buffer_memory_requirements_unchecked(create_info) }) } fn validate_buffer_memory_requirements( @@ -915,24 +918,26 @@ impl Device { let mut memory_requirements2_vk = MemoryRequirements::to_mut_vk2(&mut memory_requirements2_extensions_vk); - unsafe { - let fns = self.fns(); + let fns = self.fns(); - if self.api_version() >= Version::V1_3 { + if self.api_version() >= Version::V1_3 { + unsafe { (fns.v1_3.get_device_buffer_memory_requirements)( self.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } else { - debug_assert!(self.enabled_extensions().khr_maintenance4); + ) + }; + } else { + debug_assert!(self.enabled_extensions().khr_maintenance4); + unsafe { (fns.khr_maintenance4 .get_device_buffer_memory_requirements_khr)( self.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } + ) + }; } // Unborrow @@ -966,7 +971,7 @@ impl Device { ) -> Result> { self.validate_image_memory_requirements(&create_info, plane)?; - unsafe { Ok(self.image_memory_requirements_unchecked(create_info, plane)) } + Ok(unsafe { self.image_memory_requirements_unchecked(create_info, plane) }) } fn validate_image_memory_requirements( @@ -1130,24 +1135,26 @@ impl Device { let mut memory_requirements2_vk = MemoryRequirements::to_mut_vk2(&mut memory_requirements2_extensions_vk); - unsafe { - let fns = self.fns(); + let fns = self.fns(); - if self.api_version() >= Version::V1_3 { + if self.api_version() >= Version::V1_3 { + unsafe { (fns.v1_3.get_device_image_memory_requirements)( self.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } else { - debug_assert!(self.enabled_extensions().khr_maintenance4); + ) + }; + } else { + debug_assert!(self.enabled_extensions().khr_maintenance4); + unsafe { (fns.khr_maintenance4 .get_device_image_memory_requirements_khr)( self.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } + ) + }; } // Unborrow @@ -1270,12 +1277,10 @@ impl Device { info_vk = info_vk.object_name(object_name_vk); } - unsafe { - let fns = self.fns(); - (fns.ext_debug_utils.set_debug_utils_object_name_ext)(self.handle, &info_vk) - .result() - .map_err(VulkanError::from)?; - } + let fns = self.fns(); + unsafe { (fns.ext_debug_utils.set_debug_utils_object_name_ext)(self.handle, &info_vk) } + .result() + .map_err(VulkanError::from)?; Ok(()) } @@ -1342,18 +1347,19 @@ impl Drop for Device { fn drop(&mut self) { let fns = self.fns(); - unsafe { - for &raw_fence in self.fence_pool.lock().iter() { - (fns.v1_0.destroy_fence)(self.handle, raw_fence, ptr::null()); - } - for &raw_sem in self.semaphore_pool.lock().iter() { - (fns.v1_0.destroy_semaphore)(self.handle, raw_sem, ptr::null()); - } - for &raw_event in self.event_pool.lock().iter() { - (fns.v1_0.destroy_event)(self.handle, raw_event, ptr::null()); - } - (fns.v1_0.destroy_device)(self.handle, ptr::null()); + for &raw_fence in self.fence_pool.lock().iter() { + unsafe { (fns.v1_0.destroy_fence)(self.handle, raw_fence, ptr::null()) }; } + + for &raw_sem in self.semaphore_pool.lock().iter() { + unsafe { (fns.v1_0.destroy_semaphore)(self.handle, raw_sem, ptr::null()) }; + } + + for &raw_event in self.event_pool.lock().iter() { + unsafe { (fns.v1_0.destroy_event)(self.handle, raw_event, ptr::null()) }; + } + + unsafe { (fns.v1_0.destroy_device)(self.handle, ptr::null()) }; } } diff --git a/vulkano/src/device/physical.rs b/vulkano/src/device/physical.rs index 395304fd..b9a4d17a 100644 --- a/vulkano/src/device/physical.rs +++ b/vulkano/src/device/physical.rs @@ -427,7 +427,7 @@ impl PhysicalDevice { ) -> Result>, Validated> { self.validate_display_properties()?; - unsafe { Ok(self.display_properties_unchecked()?) } + Ok(unsafe { self.display_properties_unchecked() }?) } fn validate_display_properties(&self) -> Result<(), Box> { @@ -454,35 +454,36 @@ impl PhysicalDevice { .enabled_extensions() .khr_get_display_properties2 { - let properties_vk = unsafe { - loop { - let mut count = 0; + let properties_vk = loop { + let mut count = 0; + unsafe { (fns.khr_get_display_properties2 .get_physical_device_display_properties2_khr)( self.handle, &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut properties_vk = vec![DisplayProperties::to_mut_vk2(); count as usize]; - let result = (fns - .khr_get_display_properties2 + let mut properties_vk = vec![DisplayProperties::to_mut_vk2(); count as usize]; + let result = unsafe { + (fns.khr_get_display_properties2 .get_physical_device_display_properties2_khr)( self.handle, &mut count, properties_vk.as_mut_ptr(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - properties_vk.set_len(count as usize); - break properties_vk; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { properties_vk.set_len(count as usize) }; + break properties_vk; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -501,32 +502,34 @@ impl PhysicalDevice { }) .collect()) } else { - let properties_vk = unsafe { - loop { - let mut count = 0; + let properties_vk = loop { + let mut count = 0; + unsafe { (fns.khr_display.get_physical_device_display_properties_khr)( self.handle, &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut properties_vk = Vec::with_capacity(count as usize); - let result = (fns.khr_display.get_physical_device_display_properties_khr)( + let mut properties_vk = Vec::with_capacity(count as usize); + let result = unsafe { + (fns.khr_display.get_physical_device_display_properties_khr)( self.handle, &mut count, properties_vk.as_mut_ptr(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - properties_vk.set_len(count as usize); - break properties_vk; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { properties_vk.set_len(count as usize) }; + break properties_vk; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -553,7 +556,7 @@ impl PhysicalDevice { ) -> Result, Validated> { self.validate_display_plane_properties()?; - unsafe { Ok(self.display_plane_properties_unchecked()?) } + Ok(unsafe { self.display_plane_properties_unchecked() }?) } fn validate_display_plane_properties(&self) -> Result<(), Box> { @@ -625,36 +628,36 @@ impl PhysicalDevice { .enabled_extensions() .khr_get_display_properties2 { - let properties_vk = unsafe { - loop { - let mut count = 0; + let properties_vk = loop { + let mut count = 0; + unsafe { (fns.khr_get_display_properties2 .get_physical_device_display_plane_properties2_khr)( self.handle, &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut properties = - vec![DisplayPlanePropertiesRaw::to_mut_vk2(); count as usize]; - let result = (fns - .khr_get_display_properties2 + let mut properties = vec![DisplayPlanePropertiesRaw::to_mut_vk2(); count as usize]; + let result = unsafe { + (fns.khr_get_display_properties2 .get_physical_device_display_plane_properties2_khr)( self.handle, &mut count, properties.as_mut_ptr(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - properties.set_len(count as usize); - break properties; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { properties.set_len(count as usize) }; + break properties; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -666,35 +669,36 @@ impl PhysicalDevice { }) .collect() } else { - let properties_vk = unsafe { - loop { - let mut count = 0; + let properties_vk = loop { + let mut count = 0; + unsafe { (fns.khr_display .get_physical_device_display_plane_properties_khr)( self.handle, &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut properties = Vec::with_capacity(count as usize); - let result = (fns - .khr_display + let mut properties = Vec::with_capacity(count as usize); + let result = unsafe { + (fns.khr_display .get_physical_device_display_plane_properties_khr)( self.handle, &mut count, properties.as_mut_ptr(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - properties.set_len(count as usize); - break properties; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { properties.set_len(count as usize) }; + break properties; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -722,7 +726,7 @@ impl PhysicalDevice { ) -> Result>, Validated> { self.validate_display_plane_supported_displays(plane_index)?; - unsafe { Ok(self.display_plane_supported_displays_unchecked(plane_index)?) } + Ok(unsafe { self.display_plane_supported_displays_unchecked(plane_index) }?) } fn validate_display_plane_supported_displays( @@ -738,16 +742,15 @@ impl PhysicalDevice { })); } - let display_plane_properties_raw = unsafe { - self.display_plane_properties_raw().map_err(|_err| { + let display_plane_properties_raw = + unsafe { self.display_plane_properties_raw() }.map_err(|_err| { Box::new(ValidationError { problem: "`PhysicalDevice::display_plane_properties` \ returned an error" .into(), ..Default::default() }) - })? - }; + })?; if plane_index as usize >= display_plane_properties_raw.len() { return Err(Box::new(ValidationError { @@ -769,34 +772,36 @@ impl PhysicalDevice { ) -> Result>, VulkanError> { let fns = self.instance.fns(); - let displays_vk = unsafe { - loop { - let mut count = 0; + let displays_vk = loop { + let mut count = 0; + unsafe { (fns.khr_display.get_display_plane_supported_displays_khr)( self.handle, plane_index, &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut displays = Vec::with_capacity(count as usize); - let result = (fns.khr_display.get_display_plane_supported_displays_khr)( + let mut displays = Vec::with_capacity(count as usize); + let result = unsafe { + (fns.khr_display.get_display_plane_supported_displays_khr)( self.handle, plane_index, &mut count, displays.as_mut_ptr(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - displays.set_len(count as usize); - break displays; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { displays.set_len(count as usize) }; + break displays; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -833,7 +838,7 @@ impl PhysicalDevice { ) -> Result> { self.validate_external_buffer_properties(&info)?; - unsafe { Ok(self.external_buffer_properties_unchecked(info)) } + Ok(unsafe { self.external_buffer_properties_unchecked(info) }) } fn validate_external_buffer_properties( @@ -917,7 +922,7 @@ impl PhysicalDevice { ) -> Result> { self.validate_external_fence_properties(&info)?; - unsafe { Ok(self.external_fence_properties_unchecked(info)) } + Ok(unsafe { self.external_fence_properties_unchecked(info) }) } fn validate_external_fence_properties( @@ -1001,7 +1006,7 @@ impl PhysicalDevice { ) -> Result> { self.validate_external_semaphore_properties(&info)?; - unsafe { Ok(self.external_semaphore_properties_unchecked(info)) } + Ok(unsafe { self.external_semaphore_properties_unchecked(info) }) } fn validate_external_semaphore_properties( @@ -1081,7 +1086,7 @@ impl PhysicalDevice { ) -> Result> { self.validate_format_properties(format)?; - unsafe { Ok(self.format_properties_unchecked(format)) } + Ok(unsafe { self.format_properties_unchecked(format) }) } fn validate_format_properties(&self, format: Format) -> Result<(), Box> { @@ -1176,7 +1181,7 @@ impl PhysicalDevice { ) -> Result, Validated> { self.validate_image_format_properties(&image_format_info)?; - unsafe { Ok(self.image_format_properties_unchecked(image_format_info)?) } + Ok(unsafe { self.image_format_properties_unchecked(image_format_info) }?) } fn validate_image_format_properties( @@ -1290,7 +1295,7 @@ impl PhysicalDevice { ) -> Result, Box> { self.validate_sparse_image_format_properties(&format_info)?; - unsafe { Ok(self.sparse_image_format_properties_unchecked(format_info)) } + Ok(unsafe { self.sparse_image_format_properties_unchecked(format_info) }) } fn validate_sparse_image_format_properties( @@ -1422,7 +1427,7 @@ impl PhysicalDevice { ) -> Result> { self.validate_surface_capabilities(surface, &surface_info)?; - unsafe { Ok(self.surface_capabilities_unchecked(surface, surface_info)?) } + Ok(unsafe { self.surface_capabilities_unchecked(surface, surface_info) }?) } fn validate_surface_capabilities( @@ -1448,9 +1453,8 @@ impl PhysicalDevice { // VUID-vkGetPhysicalDeviceSurfaceCapabilities2KHR-commonparent assert_eq!(self.instance(), surface.instance()); - if !(0..self.queue_family_properties.len() as u32).any(|index| unsafe { - self.surface_support_unchecked(index, surface) - .unwrap_or_default() + if !(0..self.queue_family_properties.len() as u32).any(|index| { + unsafe { self.surface_support_unchecked(index, surface) }.unwrap_or_default() }) { return Err(Box::new(ValidationError { context: "surface".into(), @@ -1480,15 +1484,15 @@ impl PhysicalDevice { ..surface_info.clone() }, ) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::surface_present_modes` \ + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::surface_present_modes` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; if !present_modes.into_iter().any(|mode| mode == present_mode) { return Err(Box::new(ValidationError { @@ -1607,7 +1611,7 @@ impl PhysicalDevice { ) -> Result, Validated> { self.validate_surface_formats(surface, &surface_info)?; - unsafe { Ok(self.surface_formats_unchecked(surface, surface_info)?) } + Ok(unsafe { self.surface_formats_unchecked(surface, surface_info) }?) } fn validate_surface_formats( @@ -1633,9 +1637,8 @@ impl PhysicalDevice { // VUID-vkGetPhysicalDeviceSurfaceFormats2KHR-commonparent assert_eq!(self.instance(), surface.instance()); - if !(0..self.queue_family_properties.len() as u32).any(|index| unsafe { - self.surface_support_unchecked(index, surface) - .unwrap_or_default() + if !(0..self.queue_family_properties.len() as u32).any(|index| { + unsafe { self.surface_support_unchecked(index, surface) }.unwrap_or_default() }) { return Err(Box::new(ValidationError { context: "surface".into(), @@ -1665,15 +1668,15 @@ impl PhysicalDevice { ..surface_info.clone() }, ) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::surface_present_modes` \ + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::surface_present_modes` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; if !present_modes.into_iter().any(|mode| mode == present_mode) { return Err(Box::new(ValidationError { @@ -1872,7 +1875,7 @@ impl PhysicalDevice { ) -> Result, Validated> { self.validate_surface_present_modes(surface, &surface_info)?; - unsafe { Ok(self.surface_present_modes_unchecked(surface, surface_info)?) } + Ok(unsafe { self.surface_present_modes_unchecked(surface, surface_info) }?) } fn validate_surface_present_modes( @@ -1892,9 +1895,8 @@ impl PhysicalDevice { // VUID-vkGetPhysicalDeviceSurfacePresentModesKHR-commonparent assert_eq!(self.instance(), surface.instance()); - if !(0..self.queue_family_properties.len() as u32).any(|index| unsafe { - self.surface_support_unchecked(index, surface) - .unwrap_or_default() + if !(0..self.queue_family_properties.len() as u32).any(|index| { + unsafe { self.surface_support_unchecked(index, surface) }.unwrap_or_default() }) { return Err(Box::new(ValidationError { context: "surface".into(), @@ -2095,7 +2097,7 @@ impl PhysicalDevice { ) -> Result> { self.validate_surface_support(queue_family_index, surface)?; - unsafe { Ok(self.surface_support_unchecked(queue_family_index, surface)?) } + Ok(unsafe { self.surface_support_unchecked(queue_family_index, surface) }?) } fn validate_surface_support( @@ -2162,7 +2164,7 @@ impl PhysicalDevice { pub fn tool_properties(&self) -> Result, Validated> { self.validate_tool_properties()?; - unsafe { Ok(self.tool_properties_unchecked()?) } + Ok(unsafe { self.tool_properties_unchecked() }?) } fn validate_tool_properties(&self) -> Result<(), Box> { @@ -2265,7 +2267,6 @@ impl PhysicalDevice { RawDisplayHandle::AppKit(_) => true, RawDisplayHandle::Wayland(display) => { let display = display.display.as_ptr(); - unsafe { self.wayland_presentation_support(queue_family_index, display.cast()) }? } RawDisplayHandle::Windows(_display) => { @@ -2412,7 +2413,7 @@ impl PhysicalDevice { ) -> Result> { self.validate_win32_presentation_support(queue_family_index)?; - unsafe { Ok(self.win32_presentation_support_unchecked(queue_family_index)) } + Ok(unsafe { self.win32_presentation_support_unchecked(queue_family_index) }) } fn validate_win32_presentation_support( diff --git a/vulkano/src/device/private_data.rs b/vulkano/src/device/private_data.rs index b4d2abc8..0c0c3e6a 100644 --- a/vulkano/src/device/private_data.rs +++ b/vulkano/src/device/private_data.rs @@ -40,7 +40,7 @@ impl PrivateDataSlot { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -128,7 +128,7 @@ impl PrivateDataSlot { ) -> Result<(), Validated> { self.validate_set_private_data(object)?; - unsafe { Ok(self.set_private_data_unchecked(object, data)?) } + Ok(unsafe { self.set_private_data_unchecked(object, data) }?) } fn validate_set_private_data( @@ -174,11 +174,10 @@ impl PrivateDataSlot { /// If no private data was previously set, 0 is returned. pub fn get_private_data(&self, object: &T) -> u64 { let fns = self.device.fns(); + let mut output = MaybeUninit::uninit(); - unsafe { - let mut output = MaybeUninit::uninit(); - - if self.device.api_version() >= Version::V1_3 { + if self.device.api_version() >= Version::V1_3 { + unsafe { (fns.v1_3.get_private_data)( self.device.handle(), T::Handle::TYPE, @@ -186,7 +185,9 @@ impl PrivateDataSlot { self.handle, output.as_mut_ptr(), ) - } else { + } + } else { + unsafe { (fns.ext_private_data.get_private_data_ext)( self.device.handle(), T::Handle::TYPE, @@ -195,31 +196,29 @@ impl PrivateDataSlot { output.as_mut_ptr(), ) } - - output.assume_init() } + + unsafe { output.assume_init() } } } impl Drop for PrivateDataSlot { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); + let fns = self.device.fns(); - if self.device.api_version() >= Version::V1_3 { - (fns.v1_3.destroy_private_data_slot)( - self.device.handle(), - self.handle, - ptr::null(), - ); - } else { + if self.device.api_version() >= Version::V1_3 { + unsafe { + (fns.v1_3.destroy_private_data_slot)(self.device.handle(), self.handle, ptr::null()) + }; + } else { + unsafe { (fns.ext_private_data.destroy_private_data_slot_ext)( self.device.handle(), self.handle, ptr::null(), - ); - } + ) + }; } } } diff --git a/vulkano/src/device/queue.rs b/vulkano/src/device/queue.rs index ba0db366..3448d7ec 100644 --- a/vulkano/src/device/queue.rs +++ b/vulkano/src/device/queue.rs @@ -117,10 +117,8 @@ impl Queue { impl Drop for Queue { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - let _ = (fns.v1_0.queue_wait_idle)(self.handle); - } + let fns = self.device.fns(); + let _ = unsafe { (fns.v1_0.queue_wait_idle)(self.handle) }; } } @@ -212,12 +210,10 @@ impl<'a> QueueGuard<'a> { /// program. #[inline] pub fn wait_idle(&mut self) -> Result<(), VulkanError> { - unsafe { - let fns = self.queue.device.fns(); - (fns.v1_0.queue_wait_idle)(self.queue.handle) - .result() - .map_err(VulkanError::from) - } + let fns = self.queue.device.fns(); + unsafe { (fns.v1_0.queue_wait_idle)(self.queue.handle) } + .result() + .map_err(VulkanError::from) } #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] @@ -322,12 +318,13 @@ impl<'a> QueueGuard<'a> { _ne: _, } = swapchain_info; - if unsafe { - !device + let surface_support = unsafe { + device .physical_device .surface_support_unchecked(self.queue.queue_family_index, swapchain.surface()) - .unwrap_or_default() - } { + }; + + if !surface_support.unwrap_or_default() { return Err(Box::new(ValidationError { context: format!( "present_info.swapchain_infos[{}].swapchain.surface()", @@ -651,10 +648,9 @@ impl<'a> QueueGuard<'a> { ) -> Result<(), Box> { self.validate_begin_debug_utils_label(&label_info)?; - unsafe { - self.begin_debug_utils_label_unchecked(label_info); - Ok(()) - } + unsafe { self.begin_debug_utils_label_unchecked(label_info) }; + + Ok(()) } fn validate_begin_debug_utils_label( @@ -746,10 +742,9 @@ impl<'a> QueueGuard<'a> { ) -> Result<(), Box> { self.validate_insert_debug_utils_label(&label_info)?; - unsafe { - self.insert_debug_utils_label_unchecked(label_info); - Ok(()) - } + unsafe { self.insert_debug_utils_label_unchecked(label_info) }; + + Ok(()) } fn validate_insert_debug_utils_label( @@ -905,18 +900,16 @@ mod tests { #[test] fn signal_fence() { - unsafe { - let (device, queue) = gfx_dev_and_queue!(); + let (device, queue) = gfx_dev_and_queue!(); - let fence = Arc::new(Fence::new(device, Default::default()).unwrap()); - assert!(!fence.is_signaled().unwrap()); + let fence = Arc::new(Fence::new(device, Default::default()).unwrap()); + assert!(!fence.is_signaled().unwrap()); - queue - .with(|mut q| q.submit(&[Default::default()], Some(&fence))) - .unwrap(); + queue + .with(|mut q| unsafe { q.submit(&[Default::default()], Some(&fence)) }) + .unwrap(); - fence.wait(Some(Duration::from_secs(5))).unwrap(); - assert!(fence.is_signaled().unwrap()); - } + fence.wait(Some(Duration::from_secs(5))).unwrap(); + assert!(fence.is_signaled().unwrap()); } } diff --git a/vulkano/src/display.rs b/vulkano/src/display.rs index c967d3ce..b4c9be0e 100644 --- a/vulkano/src/display.rs +++ b/vulkano/src/display.rs @@ -141,9 +141,9 @@ impl Display { .enabled_extensions() .khr_get_display_properties2 { - let properties_vk = unsafe { - loop { - let mut count = 0; + let properties_vk = loop { + let mut count = 0; + unsafe { (fns.khr_get_display_properties2 .get_display_mode_properties2_khr)( self.physical_device.handle(), @@ -151,28 +151,29 @@ impl Display { &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut properties_vk = - vec![ash::vk::DisplayModeProperties2KHR::default(); count as usize]; - let result = (fns - .khr_get_display_properties2 + let mut properties_vk = + vec![ash::vk::DisplayModeProperties2KHR::default(); count as usize]; + let result = unsafe { + (fns.khr_get_display_properties2 .get_display_mode_properties2_khr)( self.physical_device.handle(), self.handle, &mut count, properties_vk.as_mut_ptr(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - properties_vk.set_len(count as usize); - break properties_vk; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { properties_vk.set_len(count as usize) }; + break properties_vk; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -193,34 +194,36 @@ impl Display { }) .collect()) } else { - let properties_vk = unsafe { - loop { - let mut count = 0; + let properties_vk = loop { + let mut count = 0; + unsafe { (fns.khr_display.get_display_mode_properties_khr)( self.physical_device.handle(), self.handle, &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut properties = Vec::with_capacity(count as usize); - let result = (fns.khr_display.get_display_mode_properties_khr)( + let mut properties = Vec::with_capacity(count as usize); + let result = unsafe { + (fns.khr_display.get_display_mode_properties_khr)( self.physical_device.handle(), self.handle, &mut count, properties.as_mut_ptr(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - properties.set_len(count as usize); - break properties; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { properties.set_len(count as usize) }; + break properties; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -355,7 +358,7 @@ impl DisplayMode { ) -> Result, Validated> { Self::validate_new(&display, &create_info)?; - unsafe { Ok(Self::new_unchecked(display, create_info)?) } + Ok(unsafe { Self::new_unchecked(display, create_info) }?) } fn validate_new( @@ -453,26 +456,23 @@ impl DisplayMode { ) -> Result> { self.validate_display_plane_capabilities(plane_index)?; - unsafe { Ok(self.display_plane_capabilities_unchecked(plane_index)?) } + Ok(unsafe { self.display_plane_capabilities_unchecked(plane_index) }?) } fn validate_display_plane_capabilities( &self, plane_index: u32, ) -> Result<(), Box> { - let display_plane_properties_raw = unsafe { - self.display - .physical_device - .display_plane_properties_raw() - .map_err(|_err| { + let display_plane_properties_raw = + unsafe { self.display.physical_device.display_plane_properties_raw() }.map_err( + |_err| { Box::new(ValidationError { - problem: "`PhysicalDevice::display_plane_properties` \ - returned an error" + problem: "`PhysicalDevice::display_plane_properties` returned an error" .into(), ..Default::default() }) - })? - }; + }, + )?; if plane_index as usize >= display_plane_properties_raw.len() { return Err(Box::new(ValidationError { @@ -492,7 +492,7 @@ impl DisplayMode { plane_index: u32, ) -> Result { self.display_plane_capabilities - .get_or_try_insert(plane_index, |&plane_index| unsafe { + .get_or_try_insert(plane_index, |&plane_index| { let fns = self.display.physical_device.instance().fns(); let mut capabilities_vk = DisplayPlaneCapabilities::to_mut_vk2(); @@ -506,21 +506,25 @@ impl DisplayMode { .mode(self.handle) .plane_index(plane_index); - (fns.khr_get_display_properties2 - .get_display_plane_capabilities2_khr)( - self.display.physical_device.handle(), - &info_vk, - &mut capabilities_vk, - ) + unsafe { + (fns.khr_get_display_properties2 + .get_display_plane_capabilities2_khr)( + self.display.physical_device.handle(), + &info_vk, + &mut capabilities_vk, + ) + } .result() .map_err(VulkanError::from)?; } else { - (fns.khr_display.get_display_plane_capabilities_khr)( - self.display.physical_device.handle(), - self.handle, - plane_index, - &mut capabilities_vk.capabilities, - ) + unsafe { + (fns.khr_display.get_display_plane_capabilities_khr)( + self.display.physical_device.handle(), + self.handle, + plane_index, + &mut capabilities_vk.capabilities, + ) + } .result() .map_err(VulkanError::from)?; } diff --git a/vulkano/src/image/mod.rs b/vulkano/src/image/mod.rs index 320462a4..f2158787 100644 --- a/vulkano/src/image/mod.rs +++ b/vulkano/src/image/mod.rs @@ -166,12 +166,10 @@ impl Image { let allocation = unsafe { ResourceMemory::from_allocation(allocator, allocation) }; // SAFETY: we just created this raw image and hasn't bound any memory to it. - let image = unsafe { - raw_image.bind_memory([allocation]).map_err(|(err, _, _)| { - err.map(AllocateImageError::BindMemory) - .map_validation(|err| err.add_context("RawImage::bind_memory")) - })? - }; + let image = unsafe { raw_image.bind_memory([allocation]) }.map_err(|(err, _, _)| { + err.map(AllocateImageError::BindMemory) + .map_validation(|err| err.add_context("RawImage::bind_memory")) + })?; Ok(Arc::new(image)) } diff --git a/vulkano/src/image/sampler/mod.rs b/vulkano/src/image/sampler/mod.rs index a779d187..5334dcd8 100644 --- a/vulkano/src/image/sampler/mod.rs +++ b/vulkano/src/image/sampler/mod.rs @@ -116,7 +116,7 @@ impl Sampler { ) -> Result, Validated> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -138,18 +138,20 @@ impl Sampler { let mut create_info_extensions_vk = create_info.to_vk_extensions(); let create_info_vk = create_info.to_vk(&mut create_info_extensions_vk); - let handle = unsafe { + let handle = { let fns = device.fns(); let mut output = MaybeUninit::uninit(); - (fns.v1_0.create_sampler)( - device.handle(), - &create_info_vk, - ptr::null(), - output.as_mut_ptr(), - ) + unsafe { + (fns.v1_0.create_sampler)( + device.handle(), + &create_info_vk, + ptr::null(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; Ok(Self::from_handle(device, handle, create_info)) @@ -507,10 +509,8 @@ impl Sampler { impl Drop for Sampler { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_sampler)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_sampler)(self.device.handle(), self.handle, ptr::null()) }; } } @@ -980,12 +980,12 @@ impl SamplerCreateInfo { assert_eq!(device, sampler_ycbcr_conversion.device().as_ref()); // Use unchecked, because all validation has been done by the SamplerYcbcrConversion. - let potential_format_features = unsafe { + let format_properties = unsafe { device .physical_device() .format_properties_unchecked(sampler_ycbcr_conversion.format()) - .potential_format_features() }; + let potential_format_features = format_properties.potential_format_features(); if !potential_format_features.intersects( FormatFeatures::SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER, diff --git a/vulkano/src/image/sampler/ycbcr.rs b/vulkano/src/image/sampler/ycbcr.rs index 4491ffc4..fd739baa 100644 --- a/vulkano/src/image/sampler/ycbcr.rs +++ b/vulkano/src/image/sampler/ycbcr.rs @@ -147,7 +147,7 @@ impl SamplerYcbcrConversion { ) -> Result, Validated> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -178,7 +178,7 @@ impl SamplerYcbcrConversion { ) -> Result, VulkanError> { let create_info_vk = create_info.to_vk(); - let handle = unsafe { + let handle = { let fns = device.fns(); let create_sampler_ycbcr_conversion = if device.api_version() >= Version::V1_1 { fns.v1_1.create_sampler_ycbcr_conversion @@ -188,15 +188,17 @@ impl SamplerYcbcrConversion { }; let mut output = MaybeUninit::uninit(); - create_sampler_ycbcr_conversion( - device.handle(), - &create_info_vk, - ptr::null(), - output.as_mut_ptr(), - ) + unsafe { + create_sampler_ycbcr_conversion( + device.handle(), + &create_info_vk, + ptr::null(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; Ok(Self::from_handle(device, handle, create_info)) @@ -312,17 +314,15 @@ impl SamplerYcbcrConversion { impl Drop for SamplerYcbcrConversion { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - let destroy_sampler_ycbcr_conversion = if self.device.api_version() >= Version::V1_1 { - fns.v1_1.destroy_sampler_ycbcr_conversion - } else { - fns.khr_sampler_ycbcr_conversion - .destroy_sampler_ycbcr_conversion_khr - }; + let fns = self.device.fns(); + let destroy_sampler_ycbcr_conversion = if self.device.api_version() >= Version::V1_1 { + fns.v1_1.destroy_sampler_ycbcr_conversion + } else { + fns.khr_sampler_ycbcr_conversion + .destroy_sampler_ycbcr_conversion_khr + }; - destroy_sampler_ycbcr_conversion(self.device.handle(), self.handle, ptr::null()); - } + unsafe { destroy_sampler_ycbcr_conversion(self.device.handle(), self.handle, ptr::null()) }; } } @@ -493,12 +493,9 @@ impl SamplerYcbcrConversionCreateInfo { } // Use unchecked, because all validation has been done above. - let potential_format_features = unsafe { - device - .physical_device() - .format_properties_unchecked(format) - .potential_format_features() - }; + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + let potential_format_features = format_properties.potential_format_features(); if !potential_format_features.intersects( FormatFeatures::MIDPOINT_CHROMA_SAMPLES | FormatFeatures::COSITED_CHROMA_SAMPLES, diff --git a/vulkano/src/image/sys.rs b/vulkano/src/image/sys.rs index f81efdee..1362b9b7 100644 --- a/vulkano/src/image/sys.rs +++ b/vulkano/src/image/sys.rs @@ -82,7 +82,7 @@ impl RawImage { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(RawImage::new_unchecked(device, create_info)?) } + Ok(unsafe { RawImage::new_unchecked(device, create_info) }?) } fn validate_new( @@ -306,33 +306,37 @@ impl RawImage { let mut memory_requirements2_vk = MemoryRequirements::to_mut_vk2(&mut memory_requirements2_extensions_vk); - unsafe { - let fns = device.fns(); + let fns = device.fns(); - if device.api_version() >= Version::V1_1 - || device.enabled_extensions().khr_get_memory_requirements2 - { - if device.api_version() >= Version::V1_1 { + if device.api_version() >= Version::V1_1 + || device.enabled_extensions().khr_get_memory_requirements2 + { + if device.api_version() >= Version::V1_1 { + unsafe { (fns.v1_1.get_image_memory_requirements2)( device.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } else { + ) + }; + } else { + unsafe { (fns.khr_get_memory_requirements2 .get_image_memory_requirements2_khr)( device.handle(), &info_vk, &mut memory_requirements2_vk, - ); - } - } else { + ) + }; + } + } else { + unsafe { (fns.v1_0.get_image_memory_requirements)( device.handle(), handle, &mut memory_requirements2_vk.memory_requirements, - ); - } + ) + }; } // Unborrow @@ -350,88 +354,95 @@ impl RawImage { #[allow(dead_code)] // Remove when sparse memory is implemented fn get_sparse_memory_requirements(&self) -> Vec { let device = &self.device; + let fns = self.device.fns(); - unsafe { - let fns = self.device.fns(); + if device.api_version() >= Version::V1_1 + || device.enabled_extensions().khr_get_memory_requirements2 + { + let info2_vk = + ash::vk::ImageSparseMemoryRequirementsInfo2::default().image(self.handle); - if device.api_version() >= Version::V1_1 - || device.enabled_extensions().khr_get_memory_requirements2 - { - let info2_vk = - ash::vk::ImageSparseMemoryRequirementsInfo2::default().image(self.handle); + let mut count = 0; - let mut count = 0; - - if device.api_version() >= Version::V1_1 { + if device.api_version() >= Version::V1_1 { + unsafe { (fns.v1_1.get_image_sparse_memory_requirements2)( device.handle(), &info2_vk, &mut count, ptr::null_mut(), - ); - } else { - (fns.khr_get_memory_requirements2 - .get_image_sparse_memory_requirements2_khr)( - device.handle(), - &info2_vk, - &mut count, - ptr::null_mut(), - ); - } - - let mut requirements2_vk = - vec![SparseImageMemoryRequirements::to_mut_vk2(); count as usize]; - - if device.api_version() >= Version::V1_1 { - (fns.v1_1.get_image_sparse_memory_requirements2)( - self.device.handle(), - &info2_vk, - &mut count, - requirements2_vk.as_mut_ptr(), - ); - } else { - (fns.khr_get_memory_requirements2 - .get_image_sparse_memory_requirements2_khr)( - self.device.handle(), - &info2_vk, - &mut count, - requirements2_vk.as_mut_ptr(), - ); - } - - requirements2_vk.set_len(count as usize); - - requirements2_vk - .iter() - .map(SparseImageMemoryRequirements::from_vk2) - .collect() + ) + }; } else { - let mut count = 0; + unsafe { + (fns.khr_get_memory_requirements2 + .get_image_sparse_memory_requirements2_khr)( + device.handle(), + &info2_vk, + &mut count, + ptr::null_mut(), + ) + }; + } + let mut requirements2_vk = + vec![SparseImageMemoryRequirements::to_mut_vk2(); count as usize]; + + if device.api_version() >= Version::V1_1 { + unsafe { + (fns.v1_1.get_image_sparse_memory_requirements2)( + self.device.handle(), + &info2_vk, + &mut count, + requirements2_vk.as_mut_ptr(), + ) + }; + } else { + unsafe { + (fns.khr_get_memory_requirements2 + .get_image_sparse_memory_requirements2_khr)( + self.device.handle(), + &info2_vk, + &mut count, + requirements2_vk.as_mut_ptr(), + ) + }; + } + + unsafe { requirements2_vk.set_len(count as usize) }; + requirements2_vk + .iter() + .map(SparseImageMemoryRequirements::from_vk2) + .collect() + } else { + let mut count = 0; + + unsafe { (fns.v1_0.get_image_sparse_memory_requirements)( device.handle(), self.handle, &mut count, ptr::null_mut(), - ); + ) + }; - let mut requirements_vk = - vec![SparseImageMemoryRequirements::to_mut_vk(); count as usize]; + let mut requirements_vk = + vec![SparseImageMemoryRequirements::to_mut_vk(); count as usize]; + unsafe { (fns.v1_0.get_image_sparse_memory_requirements)( device.handle(), self.handle, &mut count, requirements_vk.as_mut_ptr(), - ); + ) + }; - requirements_vk.set_len(count as usize); - - requirements_vk - .iter() - .map(SparseImageMemoryRequirements::from_vk) - .collect() - } + unsafe { requirements_vk.set_len(count as usize) }; + requirements_vk + .iter() + .map(SparseImageMemoryRequirements::from_vk) + .collect() } } @@ -1159,7 +1170,7 @@ impl RawImage { ) -> Result> { self.validate_subresource_layout(aspect, mip_level, array_layer)?; - unsafe { Ok(self.subresource_layout_unchecked(aspect, mip_level, array_layer)) } + Ok(unsafe { self.subresource_layout_unchecked(aspect, mip_level, array_layer) }) } fn validate_subresource_layout( @@ -1417,10 +1428,8 @@ impl Drop for RawImage { return; } - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_image)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_image)(self.device.handle(), self.handle, ptr::null()) }; } } @@ -2606,33 +2615,32 @@ impl ImageCreateInfo { for drm_format_modifier in iter_or_none(drm_format_modifiers.iter().copied()) { for external_memory_handle_type in iter_or_none(external_memory_handle_types) { let image_format_properties = unsafe { - physical_device - .image_format_properties_unchecked(ImageFormatInfo { - flags, - format, - image_type, - tiling, - usage, - stencil_usage, - external_memory_handle_type, - drm_format_modifier_info: drm_format_modifier.map( - |drm_format_modifier| ImageDrmFormatModifierInfo { - drm_format_modifier, - sharing: sharing.clone(), - ..Default::default() - }, - ), - ..Default::default() - }) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::image_format_properties` \ - returned an error" - .into(), + physical_device.image_format_properties_unchecked(ImageFormatInfo { + flags, + format, + image_type, + tiling, + usage, + stencil_usage, + external_memory_handle_type, + drm_format_modifier_info: drm_format_modifier.map(|drm_format_modifier| { + ImageDrmFormatModifierInfo { + drm_format_modifier, + sharing: sharing.clone(), ..Default::default() - }) - })? - }; + } + }), + ..Default::default() + }) + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::image_format_properties` \ + returned an error" + .into(), + ..Default::default() + }) + })?; let image_format_properties = image_format_properties.ok_or_else(|| Box::new(ValidationError { problem: "the combination of parameters of this image is not \ diff --git a/vulkano/src/image/view.rs b/vulkano/src/image/view.rs index fb040743..c079ba0e 100644 --- a/vulkano/src/image/view.rs +++ b/vulkano/src/image/view.rs @@ -55,7 +55,7 @@ impl ImageView { ) -> Result, Validated> { Self::validate_new(&image, &create_info)?; - unsafe { Ok(Self::new_unchecked(image, create_info)?) } + Ok(unsafe { Self::new_unchecked(image, create_info) }?) } fn validate_new( @@ -729,11 +729,9 @@ impl ImageView { impl Drop for ImageView { #[inline] fn drop(&mut self) { - unsafe { - let device = self.device(); - let fns = device.fns(); - (fns.v1_0.destroy_image_view)(device.handle(), self.handle, ptr::null()); - } + let device = self.device(); + let fns = device.fns(); + unsafe { (fns.v1_0.destroy_image_view)(device.handle(), self.handle, ptr::null()) }; } } diff --git a/vulkano/src/instance/debug.rs b/vulkano/src/instance/debug.rs index 9a0ca0e6..13cc5d7d 100644 --- a/vulkano/src/instance/debug.rs +++ b/vulkano/src/instance/debug.rs @@ -18,17 +18,15 @@ //! DebugUtilsMessenger, DebugUtilsMessengerCallback, DebugUtilsMessengerCreateInfo, //! }; //! -//! let _callback = unsafe { -//! DebugUtilsMessenger::new( -//! instance, -//! DebugUtilsMessengerCreateInfo::user_callback(DebugUtilsMessengerCallback::new( -//! |message_severity, message_type, callback_data| { -//! println!("Debug callback: {:?}", callback_data.message); -//! }, -//! )), -//! ) -//! .ok() -//! }; +//! let _callback = DebugUtilsMessenger::new( +//! instance, +//! DebugUtilsMessengerCreateInfo::user_callback(unsafe { +//! DebugUtilsMessengerCallback::new(|message_severity, message_type, callback_data| { +//! println!("Debug callback: {:?}", callback_data.message); +//! }) +//! }), +//! ) +//! .ok(); //! ``` //! //! Note that you must keep the `_callback` object alive for as long as you want your callback to @@ -69,7 +67,7 @@ impl DebugUtilsMessenger { ) -> Result> { Self::validate_new(&instance, &create_info)?; - unsafe { Ok(Self::new_unchecked(instance, create_info)?) } + Ok(unsafe { Self::new_unchecked(instance, create_info) }?) } fn validate_new( @@ -124,14 +122,14 @@ impl DebugUtilsMessenger { impl Drop for DebugUtilsMessenger { #[inline] fn drop(&mut self) { + let fns = self.instance.fns(); unsafe { - let fns = self.instance.fns(); (fns.ext_debug_utils.destroy_debug_utils_messenger_ext)( self.instance.handle(), self.handle, ptr::null(), - ); - } + ) + }; } } @@ -424,11 +422,12 @@ impl<'a> Iterator for DebugUtilsMessengerCallbackLabelIter<'a> { type Item = DebugUtilsMessengerCallbackLabel<'a>; fn next(&mut self) -> Option { - self.0.next().map(|label| unsafe { - DebugUtilsMessengerCallbackLabel { - label_name: label.label_name_as_c_str().unwrap().to_str().unwrap(), - color: &label.color, - } + self.0.next().map(|label| DebugUtilsMessengerCallbackLabel { + label_name: unsafe { label.label_name_as_c_str() } + .unwrap() + .to_str() + .unwrap(), + color: &label.color, }) } } @@ -455,7 +454,7 @@ impl<'a> Iterator for DebugUtilsMessengerCallbackObjectNameInfoIter<'a> { type Item = DebugUtilsMessengerCallbackObjectNameInfo<'a>; fn next(&mut self) -> Option { - self.0.next().map(|info| unsafe { + self.0.next().map(|info| { let &ash::vk::DebugUtilsObjectNameInfoEXT { object_type, object_handle, @@ -466,9 +465,9 @@ impl<'a> Iterator for DebugUtilsMessengerCallbackObjectNameInfoIter<'a> { DebugUtilsMessengerCallbackObjectNameInfo { object_type, object_handle, - object_name: p_object_name - .as_ref() - .map(|p_object_name| CStr::from_ptr(p_object_name).to_str().unwrap()), + object_name: unsafe { p_object_name.as_ref() }.map(|p_object_name| { + unsafe { CStr::from_ptr(p_object_name) }.to_str().unwrap() + }), } }) } @@ -673,20 +672,18 @@ mod tests { } }; - let callback = unsafe { - DebugUtilsMessenger::new( - instance, - DebugUtilsMessengerCreateInfo { - message_severity: DebugUtilsMessageSeverity::ERROR, - message_type: DebugUtilsMessageType::GENERAL - | DebugUtilsMessageType::VALIDATION - | DebugUtilsMessageType::PERFORMANCE, - ..DebugUtilsMessengerCreateInfo::user_callback( - DebugUtilsMessengerCallback::new(|_, _, _| {}), - ) - }, - ) - } + let callback = DebugUtilsMessenger::new( + instance, + DebugUtilsMessengerCreateInfo { + message_severity: DebugUtilsMessageSeverity::ERROR, + message_type: DebugUtilsMessageType::GENERAL + | DebugUtilsMessageType::VALIDATION + | DebugUtilsMessageType::PERFORMANCE, + ..DebugUtilsMessengerCreateInfo::user_callback(unsafe { + DebugUtilsMessengerCallback::new(|_, _, _| {}) + }) + }, + ) .unwrap(); thread::spawn(move || { drop(callback); diff --git a/vulkano/src/instance/mod.rs b/vulkano/src/instance/mod.rs index 47978f71..f0826616 100644 --- a/vulkano/src/instance/mod.rs +++ b/vulkano/src/instance/mod.rs @@ -295,7 +295,7 @@ impl Instance { Self::validate_new(&library, &create_info)?; - unsafe { Ok(Self::new_unchecked(library, create_info)?) } + Ok(unsafe { Self::new_unchecked(library, create_info) }?) } fn validate_new( @@ -536,41 +536,40 @@ impl Instance { ) -> Result>, VulkanError> { let fns = self.fns(); - unsafe { - let handles = loop { - let mut count = 0; + let handles = loop { + let mut count = 0; + unsafe { (fns.v1_0.enumerate_physical_devices)(self.handle, &mut count, ptr::null_mut()) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut handles = Vec::with_capacity(count as usize); - let result = (fns.v1_0.enumerate_physical_devices)( - self.handle, - &mut count, - handles.as_mut_ptr(), - ); - - match result { - ash::vk::Result::SUCCESS => { - handles.set_len(count as usize); - break handles; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), - } + let mut handles = Vec::with_capacity(count as usize); + let result = unsafe { + (fns.v1_0.enumerate_physical_devices)(self.handle, &mut count, handles.as_mut_ptr()) }; - let physical_devices: SmallVec<[_; 4]> = handles - .into_iter() - .map(|handle| { - self.physical_devices.get_or_try_insert(handle, |&handle| { + match result { + ash::vk::Result::SUCCESS => { + unsafe { handles.set_len(count as usize) }; + break handles; + } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), + } + }; + + let physical_devices: SmallVec<[_; 4]> = handles + .into_iter() + .map(|handle| { + self.physical_devices + .get_or_try_insert(handle, |&handle| unsafe { PhysicalDevice::from_handle(self.clone(), handle) }) - }) - .collect::>()?; + }) + .collect::>()?; - Ok(physical_devices.into_iter()) - } + Ok(physical_devices.into_iter()) } /// Returns an iterator that enumerates the groups of physical devices available. All @@ -595,7 +594,7 @@ impl Instance { { self.validate_enumerate_physical_device_groups()?; - unsafe { Ok(self.enumerate_physical_device_groups_unchecked()?) } + Ok(unsafe { self.enumerate_physical_device_groups_unchecked() }?) } fn validate_enumerate_physical_device_groups(&self) -> Result<(), Box> { @@ -735,10 +734,7 @@ impl Drop for Instance { #[inline] fn drop(&mut self) { let fns = self.fns(); - - unsafe { - (fns.v1_0.destroy_instance)(self.handle, ptr::null()); - } + unsafe { (fns.v1_0.destroy_instance)(self.handle, ptr::null()) }; } } diff --git a/vulkano/src/library.rs b/vulkano/src/library.rs index 1cb4656e..022cbadc 100644 --- a/vulkano/src/library.rs +++ b/vulkano/src/library.rs @@ -90,14 +90,13 @@ impl VulkanLibrary { /// Loads a custom Vulkan library. pub fn with_loader(loader: impl Loader + 'static) -> Result, LoadingError> { - let fns = EntryFunctions::load(|name| unsafe { - loader - .get_instance_proc_addr(ash::vk::Instance::null(), name.as_ptr()) + let fns = EntryFunctions::load(|name| { + unsafe { loader.get_instance_proc_addr(ash::vk::Instance::null(), name.as_ptr()) } .map_or(ptr::null(), |func| func as _) }); - let api_version = unsafe { Self::get_api_version(&loader)? }; - let extension_properties = unsafe { Self::get_extension_properties(&fns, None)? }; + let api_version = unsafe { Self::get_api_version(&loader) }?; + let extension_properties = unsafe { Self::get_extension_properties(&fns, None) }?; let supported_extensions = extension_properties .iter() .map(|property| property.extension_name.as_str()) @@ -227,27 +226,24 @@ impl VulkanLibrary { ) -> Result, VulkanError> { let fns = self.fns(); - let layer_properties = unsafe { - loop { - let mut count = 0; - (fns.v1_0.enumerate_instance_layer_properties)(&mut count, ptr::null_mut()) - .result() - .map_err(VulkanError::from)?; + let layer_properties = loop { + let mut count = 0; + unsafe { (fns.v1_0.enumerate_instance_layer_properties)(&mut count, ptr::null_mut()) } + .result() + .map_err(VulkanError::from)?; - let mut properties = Vec::with_capacity(count as usize); - let result = (fns.v1_0.enumerate_instance_layer_properties)( - &mut count, - properties.as_mut_ptr(), - ); + let mut properties = Vec::with_capacity(count as usize); + let result = unsafe { + (fns.v1_0.enumerate_instance_layer_properties)(&mut count, properties.as_mut_ptr()) + }; - match result { - ash::vk::Result::SUCCESS => { - properties.set_len(count as usize); - break properties; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { properties.set_len(count as usize) }; + break properties; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -449,11 +445,9 @@ mod tests { #[test] fn dl_open_error() { - unsafe { - match DynamicLibraryLoader::new("_non_existing_library.void") { - Err(LoadingError::LibraryLoadFailure(_)) => (), - _ => panic!(), - } + match unsafe { DynamicLibraryLoader::new("_non_existing_library.void") } { + Err(LoadingError::LibraryLoadFailure(_)) => (), + _ => panic!(), } } } diff --git a/vulkano/src/memory/allocator/mod.rs b/vulkano/src/memory/allocator/mod.rs index d4187b47..cca4c2ab 100644 --- a/vulkano/src/memory/allocator/mod.rs +++ b/vulkano/src/memory/allocator/mod.rs @@ -1099,8 +1099,8 @@ impl GenericMemoryAllocator { offset: 0, size: memory.allocation_size(), _ne: crate::NonExhaustive(()), - })?; - } + }) + }?; } Ok(Arc::new(memory)) diff --git a/vulkano/src/memory/device_memory.rs b/vulkano/src/memory/device_memory.rs index b7cb2281..b8be8a90 100644 --- a/vulkano/src/memory/device_memory.rs +++ b/vulkano/src/memory/device_memory.rs @@ -84,7 +84,7 @@ impl DeviceMemory { Self::validate_allocate(&device, &allocate_info, None)?; - unsafe { Ok(Self::allocate_unchecked(device, allocate_info, None)?) } + Ok(unsafe { Self::allocate_unchecked(device, allocate_info, None) }?) } /// Imports a block of memory from an external source. @@ -331,7 +331,7 @@ impl DeviceMemory { pub fn map(&mut self, map_info: MemoryMapInfo) -> Result<(), Validated> { self.validate_map(&map_info, None)?; - unsafe { Ok(self.map_unchecked(map_info)?) } + Ok(unsafe { self.map_unchecked(map_info) }?) } #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] @@ -366,7 +366,7 @@ impl DeviceMemory { ) -> Result<(), Validated> { self.validate_map(&map_info, Some(placed_address))?; - unsafe { Ok(self.map_placed_unchecked(map_info, placed_address)?) } + Ok(unsafe { self.map_placed_unchecked(map_info, placed_address) }?) } #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] @@ -644,7 +644,7 @@ impl DeviceMemory { pub fn commitment(&self) -> Result> { self.validate_commitment()?; - unsafe { Ok(self.commitment_unchecked()) } + Ok(unsafe { self.commitment_unchecked() }) } fn validate_commitment(&self) -> Result<(), Box> { @@ -693,7 +693,7 @@ impl DeviceMemory { ) -> Result> { self.validate_export_fd(handle_type)?; - unsafe { Ok(self.export_fd_unchecked(handle_type)?) } + Ok(unsafe { self.export_fd_unchecked(handle_type) }?) } fn validate_export_fd( @@ -767,11 +767,9 @@ impl DeviceMemory { impl Drop for DeviceMemory { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.free_memory)(self.device.handle(), self.handle, ptr::null()); - self.device.allocation_count.fetch_sub(1, Ordering::Release); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.free_memory)(self.device.handle(), self.handle, ptr::null()) }; + self.device.allocation_count.fetch_sub(1, Ordering::Release); } } @@ -2022,7 +2020,7 @@ impl MappedDeviceMemory { ) -> Result> { Self::validate_new(&memory, range.clone())?; - unsafe { Ok(Self::new_unchecked(memory, range)?) } + Ok(unsafe { Self::new_unchecked(memory, range) }?) } fn validate_new( @@ -2110,20 +2108,22 @@ impl MappedDeviceMemory { let device = memory.device(); - let pointer = unsafe { + let pointer = { let fns = device.fns(); let mut output = MaybeUninit::uninit(); - (fns.v1_0.map_memory)( - device.handle(), - memory.handle, - range.start, - range.end - range.start, - ash::vk::MemoryMapFlags::empty(), - output.as_mut_ptr(), - ) + unsafe { + (fns.v1_0.map_memory)( + device.handle(), + memory.handle, + range.start, + range.end - range.start, + ash::vk::MemoryMapFlags::empty(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; let atom_size = device.physical_device().properties().non_coherent_atom_size; @@ -2145,11 +2145,9 @@ impl MappedDeviceMemory { /// Unmaps the memory. It will no longer be accessible from the CPU. #[inline] pub fn unmap(self) -> DeviceMemory { - unsafe { - let device = self.memory.device(); - let fns = device.fns(); - (fns.v1_0.unmap_memory)(device.handle(), self.memory.handle); - } + let device = self.memory.device(); + let fns = device.fns(); + unsafe { (fns.v1_0.unmap_memory)(device.handle(), self.memory.handle) }; self.memory } @@ -2583,33 +2581,30 @@ mod tests { .unwrap(); let address = unsafe { - let address = libc::mmap( + libc::mmap( ptr::null_mut(), 16 * 1024, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, -1, 0, - ); - - if address as i64 == -1 { - panic!("failed to map memory") - } - - address + ) }; - unsafe { - memory - .map_placed( - MemoryMapInfo { - flags: MemoryMapFlags::PLACED, - size: memory.allocation_size, - ..Default::default() - }, - NonNull::new(address).unwrap(), - ) - .unwrap(); + if address as i64 == -1 { + panic!("failed to map memory") } + + unsafe { + memory.map_placed( + MemoryMapInfo { + flags: MemoryMapFlags::PLACED, + size: memory.allocation_size, + ..Default::default() + }, + NonNull::new(address).unwrap(), + ) + } + .unwrap(); } } diff --git a/vulkano/src/pipeline/cache.rs b/vulkano/src/pipeline/cache.rs index 4215cfdb..1cff452b 100644 --- a/vulkano/src/pipeline/cache.rs +++ b/vulkano/src/pipeline/cache.rs @@ -77,8 +77,8 @@ impl PipelineCache { /// ..Default::default() /// }, /// ) - /// .unwrap() - /// }; + /// } + /// .unwrap(); /// ``` #[inline] pub unsafe fn new( @@ -183,34 +183,36 @@ impl PipelineCache { pub fn get_data(&self) -> Result, VulkanError> { let fns = self.device.fns(); - let data = unsafe { - loop { - let mut count = 0; + let data = loop { + let mut count = 0; + unsafe { (fns.v1_0.get_pipeline_cache_data)( self.device.handle(), self.handle, &mut count, ptr::null_mut(), ) - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - let mut data: Vec = Vec::with_capacity(count); - let result = (fns.v1_0.get_pipeline_cache_data)( + let mut data: Vec = Vec::with_capacity(count); + let result = unsafe { + (fns.v1_0.get_pipeline_cache_data)( self.device.handle(), self.handle, &mut count, data.as_mut_ptr().cast(), - ); + ) + }; - match result { - ash::vk::Result::SUCCESS => { - data.set_len(count); - break data; - } - ash::vk::Result::INCOMPLETE => (), - err => return Err(VulkanError::from(err)), + match result { + ash::vk::Result::SUCCESS => { + unsafe { data.set_len(count) }; + break data; } + ash::vk::Result::INCOMPLETE => (), + err => return Err(VulkanError::from(err)), } }; @@ -229,7 +231,7 @@ impl PipelineCache { let src_caches: SmallVec<[_; 8]> = src_caches.into_iter().collect(); self.validate_merge(&src_caches)?; - unsafe { Ok(self.merge_unchecked(src_caches)?) } + Ok(unsafe { self.merge_unchecked(src_caches) }?) } fn validate_merge(&self, src_caches: &[&PipelineCache]) -> Result<(), Box> { @@ -272,10 +274,10 @@ impl PipelineCache { impl Drop for PipelineCache { #[inline] fn drop(&mut self) { + let fns = self.device.fns(); unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_pipeline_cache)(self.device.handle(), self.handle, ptr::null()); - } + (fns.v1_0.destroy_pipeline_cache)(self.device.handle(), self.handle, ptr::null()) + }; } } @@ -393,7 +395,7 @@ mod tests { #[test] fn merge_self_forbidden() { let (device, _queue) = gfx_dev_and_queue!(); - let pipeline = unsafe { PipelineCache::new(device, Default::default()).unwrap() }; + let pipeline = unsafe { PipelineCache::new(device, Default::default()) }.unwrap(); match pipeline.merge([pipeline.as_ref()]) { Err(_) => (), Ok(_) => panic!(), @@ -404,9 +406,9 @@ mod tests { fn cache_returns_same_data() { let (device, _queue) = gfx_dev_and_queue!(); - let cache = unsafe { PipelineCache::new(device.clone(), Default::default()).unwrap() }; + let cache = unsafe { PipelineCache::new(device.clone(), Default::default()) }.unwrap(); - let cs = unsafe { + let cs = { /* * #version 450 * void main() { @@ -419,7 +421,8 @@ mod tests { 3, 131320, 5, 65789, 65592, ]; let module = - ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)).unwrap(); + unsafe { ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)) } + .unwrap(); module.entry_point("main").unwrap() }; @@ -450,10 +453,10 @@ mod tests { fn cache_returns_different_data() { let (device, _queue) = gfx_dev_and_queue!(); - let cache = unsafe { PipelineCache::new(device.clone(), Default::default()).unwrap() }; + let cache = unsafe { PipelineCache::new(device.clone(), Default::default()) }.unwrap(); let _first_pipeline = { - let cs = unsafe { + let cs = { /* * #version 450 * void main() { @@ -465,9 +468,10 @@ mod tests { 1, 196611, 2, 450, 262149, 4, 1852399981, 0, 131091, 2, 196641, 3, 2, 327734, 2, 4, 0, 3, 131320, 5, 65789, 65592, ]; - let module = + let module = unsafe { ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)) - .unwrap(); + } + .unwrap(); module.entry_point("main").unwrap() }; @@ -490,7 +494,7 @@ mod tests { let cache_data = cache.get_data().unwrap(); let _second_pipeline = { - let cs = unsafe { + let cs = { /* * #version 450 * @@ -508,9 +512,10 @@ mod tests { 327734, 2, 4, 0, 3, 131320, 5, 262203, 7, 8, 7, 327745, 13, 14, 11, 12, 262205, 6, 15, 14, 196670, 8, 15, 65789, 65592, ]; - let module = + let module = unsafe { ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)) - .unwrap(); + } + .unwrap(); module.entry_point("main").unwrap() }; @@ -543,9 +548,9 @@ mod tests { fn cache_data_does_not_change() { let (device, _queue) = gfx_dev_and_queue!(); - let cache = unsafe { PipelineCache::new(device.clone(), Default::default()).unwrap() }; + let cache = unsafe { PipelineCache::new(device.clone(), Default::default()) }.unwrap(); - let cs = unsafe { + let cs = { /* * #version 450 * void main() { @@ -558,7 +563,8 @@ mod tests { 3, 131320, 5, 65789, 65592, ]; let module = - ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)).unwrap(); + unsafe { ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)) } + .unwrap(); module.entry_point("main").unwrap() }; diff --git a/vulkano/src/pipeline/compute.rs b/vulkano/src/pipeline/compute.rs index 2edf6ce6..8766d0f0 100644 --- a/vulkano/src/pipeline/compute.rs +++ b/vulkano/src/pipeline/compute.rs @@ -59,7 +59,7 @@ impl ComputePipeline { ) -> Result, Validated> { Self::validate_new(&device, cache.as_ref().map(AsRef::as_ref), &create_info)?; - unsafe { Ok(Self::new_unchecked(device, cache, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, cache, create_info) }?) } fn validate_new( @@ -213,10 +213,8 @@ unsafe impl DeviceOwned for ComputePipeline { impl Drop for ComputePipeline { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_pipeline)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_pipeline)(self.device.handle(), self.handle, ptr::null()) }; } } @@ -460,7 +458,7 @@ mod tests { let (device, queue) = gfx_dev_and_queue!(); - let cs = unsafe { + let cs = { /* #version 450 @@ -487,7 +485,8 @@ mod tests { 4, 0, 3, 131320, 5, 327745, 12, 13, 9, 10, 196670, 13, 11, 65789, 65592, ]; let module = - ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)).unwrap(); + unsafe { ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)) } + .unwrap(); module .specialize([(83, 0x12345678i32.into())].into_iter().collect()) .unwrap() @@ -560,10 +559,7 @@ mod tests { set, ) .unwrap(); - - unsafe { - cbb.dispatch([1, 1, 1]).unwrap(); - } + unsafe { cbb.dispatch([1, 1, 1]) }.unwrap(); let cb = cbb.build().unwrap(); @@ -596,7 +592,7 @@ mod tests { return; } - let cs = unsafe { + let cs = { /* #version 450 @@ -636,7 +632,8 @@ mod tests { 131321, 17, 131320, 17, 65789, 65592, ]; let module = - ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)).unwrap(); + unsafe { ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&MODULE)) } + .unwrap(); module.entry_point("main").unwrap() }; @@ -711,10 +708,7 @@ mod tests { set, ) .unwrap(); - - unsafe { - cbb.dispatch([128, 1, 1]).unwrap(); - } + unsafe { cbb.dispatch([128, 1, 1]) }.unwrap(); let cb = cbb.build().unwrap(); diff --git a/vulkano/src/pipeline/graphics/mod.rs b/vulkano/src/pipeline/graphics/mod.rs index e3eb1c85..a90633b2 100644 --- a/vulkano/src/pipeline/graphics/mod.rs +++ b/vulkano/src/pipeline/graphics/mod.rs @@ -180,7 +180,7 @@ impl GraphicsPipeline { ) -> Result, Validated> { Self::validate_new(&device, cache.as_ref().map(AsRef::as_ref), &create_info)?; - unsafe { Ok(Self::new_unchecked(device, cache, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, cache, create_info) }?) } fn validate_new( @@ -611,10 +611,8 @@ unsafe impl VulkanObject for GraphicsPipeline { impl Drop for GraphicsPipeline { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_pipeline)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_pipeline)(self.device.handle(), self.handle, ptr::null()) }; } } @@ -2307,10 +2305,10 @@ impl GraphicsPipelineCreateInfo { } }; - if !attachment_format.map_or(false, |format| unsafe { - device - .physical_device() - .format_properties_unchecked(format) + if !attachment_format.map_or(false, |format| { + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + format_properties .potential_format_features() .intersects(FormatFeatures::COLOR_ATTACHMENT_BLEND) }) { diff --git a/vulkano/src/pipeline/graphics/subpass.rs b/vulkano/src/pipeline/graphics/subpass.rs index a85717ed..4779ed89 100644 --- a/vulkano/src/pipeline/graphics/subpass.rs +++ b/vulkano/src/pipeline/graphics/subpass.rs @@ -225,7 +225,10 @@ impl PipelineRenderingCreateInfo { })); } - if !unsafe { device.physical_device().format_properties_unchecked(format) } + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + + if !format_properties .potential_format_features() .intersects(FormatFeatures::COLOR_ATTACHMENT) { @@ -254,7 +257,10 @@ impl PipelineRenderingCreateInfo { })); } - if !unsafe { device.physical_device().format_properties_unchecked(format) } + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + + if !format_properties .potential_format_features() .intersects(FormatFeatures::DEPTH_STENCIL_ATTACHMENT) { @@ -292,7 +298,10 @@ impl PipelineRenderingCreateInfo { })); } - if !unsafe { device.physical_device().format_properties_unchecked(format) } + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + + if !format_properties .potential_format_features() .intersects(FormatFeatures::DEPTH_STENCIL_ATTACHMENT) { diff --git a/vulkano/src/pipeline/graphics/vertex_input/mod.rs b/vulkano/src/pipeline/graphics/vertex_input/mod.rs index 7c1b1f44..286d2757 100644 --- a/vulkano/src/pipeline/graphics/vertex_input/mod.rs +++ b/vulkano/src/pipeline/graphics/vertex_input/mod.rs @@ -795,12 +795,9 @@ impl VertexInputAttributeDescription { })); } - let format_features = unsafe { - device - .physical_device() - .format_properties_unchecked(format) - .buffer_features - }; + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + let format_features = format_properties.buffer_features; if !format_features.intersects(FormatFeatures::VERTEX_BUFFER) { return Err(Box::new(ValidationError { diff --git a/vulkano/src/pipeline/layout.rs b/vulkano/src/pipeline/layout.rs index c0cc8200..6a1363e8 100644 --- a/vulkano/src/pipeline/layout.rs +++ b/vulkano/src/pipeline/layout.rs @@ -103,7 +103,7 @@ impl PipelineLayout { ) -> Result, Validated> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -353,10 +353,10 @@ impl PipelineLayout { impl Drop for PipelineLayout { #[inline] fn drop(&mut self) { + let fns = self.device.fns(); unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_pipeline_layout)(self.device.handle(), self.handle, ptr::null()); - } + (fns.v1_0.destroy_pipeline_layout)(self.device.handle(), self.handle, ptr::null()) + }; } } diff --git a/vulkano/src/query.rs b/vulkano/src/query.rs index ac411976..b2f5a066 100644 --- a/vulkano/src/query.rs +++ b/vulkano/src/query.rs @@ -41,7 +41,7 @@ impl QueryPool { ) -> Result, Validated> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -62,18 +62,20 @@ impl QueryPool { ) -> Result, VulkanError> { let create_info_vk = create_info.to_vk(); - let handle = unsafe { - let fns = device.fns(); + let fns = device.fns(); + let handle = { let mut output = MaybeUninit::uninit(); - (fns.v1_0.create_query_pool)( - device.handle(), - &create_info_vk, - ptr::null(), - output.as_mut_ptr(), - ) + unsafe { + (fns.v1_0.create_query_pool)( + device.handle(), + &create_info_vk, + ptr::null(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; Ok(Self::from_handle(device, handle, create_info)) @@ -169,7 +171,7 @@ impl QueryPool { { self.validate_get_results(range.clone(), destination, flags)?; - unsafe { Ok(self.get_results_unchecked(range, destination, flags)?) } + Ok(unsafe { self.get_results_unchecked(range, destination, flags) }?) } fn validate_get_results( @@ -264,8 +266,8 @@ impl QueryPool { let per_query_len = self.result_len(flags); let stride = per_query_len * std::mem::size_of::() as DeviceSize; + let fns = self.device.fns(); let result = unsafe { - let fns = self.device.fns(); (fns.v1_0.get_query_pool_results)( self.device.handle(), self.handle(), @@ -301,9 +303,7 @@ impl QueryPool { pub unsafe fn reset(&self, range: Range) -> Result<(), Box> { self.validate_reset(range.clone())?; - unsafe { - self.reset_unchecked(range); - } + unsafe { self.reset_unchecked(range) }; Ok(()) } @@ -372,10 +372,8 @@ impl QueryPool { impl Drop for QueryPool { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_query_pool)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_query_pool)(self.device.handle(), self.handle, ptr::null()) }; } } diff --git a/vulkano/src/render_pass/framebuffer.rs b/vulkano/src/render_pass/framebuffer.rs index d37052c8..434b12d7 100644 --- a/vulkano/src/render_pass/framebuffer.rs +++ b/vulkano/src/render_pass/framebuffer.rs @@ -56,7 +56,7 @@ impl Framebuffer { create_info.set_auto_extent_layers(&render_pass); Self::validate_new(&render_pass, &create_info)?; - unsafe { Ok(Self::new_unchecked(render_pass, create_info)?) } + Ok(unsafe { Self::new_unchecked(render_pass, create_info) }?) } fn validate_new( @@ -250,18 +250,20 @@ impl Framebuffer { let create_info_fields1_vk = create_info.to_vk_fields1(); let create_info_vk = create_info.to_vk(render_pass.handle(), &create_info_fields1_vk); - let handle = unsafe { + let handle = { let fns = render_pass.device().fns(); let mut output = MaybeUninit::uninit(); - (fns.v1_0.create_framebuffer)( - render_pass.device().handle(), - &create_info_vk, - ptr::null(), - output.as_mut_ptr(), - ) + unsafe { + (fns.v1_0.create_framebuffer)( + render_pass.device().handle(), + &create_info_vk, + ptr::null(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; Ok(Self::from_handle(render_pass, handle, create_info)) @@ -347,10 +349,8 @@ impl Framebuffer { impl Drop for Framebuffer { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device().fns(); - (fns.v1_0.destroy_framebuffer)(self.device().handle(), self.handle, ptr::null()); - } + let fns = self.device().fns(); + unsafe { (fns.v1_0.destroy_framebuffer)(self.device().handle(), self.handle, ptr::null()) }; } } diff --git a/vulkano/src/render_pass/mod.rs b/vulkano/src/render_pass/mod.rs index deb2c5db..b46a760e 100644 --- a/vulkano/src/render_pass/mod.rs +++ b/vulkano/src/render_pass/mod.rs @@ -141,7 +141,7 @@ impl RenderPass { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -174,32 +174,34 @@ impl RenderPass { } } - let handle = unsafe { - if device.api_version() >= Version::V1_2 - || device.enabled_extensions().khr_create_renderpass2 - { - let mut create_info_fields2_extensions_vk = create_info.to_vk2_fields2_extensions(); - let create_info_fields2_vk = - create_info.to_vk2_fields2(&mut create_info_fields2_extensions_vk); - let mut create_info_fields1_extensions_vk = - create_info.to_vk2_fields1_extensions(&create_info_fields2_vk); - let create_info_fields1_vk = create_info.to_vk2_fields1( - &create_info_fields2_vk, - &mut create_info_fields1_extensions_vk, - ); - let create_info_vk = create_info.to_vk2(&create_info_fields1_vk); + let handle = if device.api_version() >= Version::V1_2 + || device.enabled_extensions().khr_create_renderpass2 + { + let mut create_info_fields2_extensions_vk = create_info.to_vk2_fields2_extensions(); + let create_info_fields2_vk = + create_info.to_vk2_fields2(&mut create_info_fields2_extensions_vk); + let mut create_info_fields1_extensions_vk = + create_info.to_vk2_fields1_extensions(&create_info_fields2_vk); + let create_info_fields1_vk = create_info.to_vk2_fields1( + &create_info_fields2_vk, + &mut create_info_fields1_extensions_vk, + ); + let create_info_vk = create_info.to_vk2(&create_info_fields1_vk); - let fns = device.fns(); - let mut output = MaybeUninit::uninit(); + let fns = device.fns(); + let mut output = MaybeUninit::uninit(); - if device.api_version() >= Version::V1_2 { + if device.api_version() >= Version::V1_2 { + unsafe { (fns.v1_2.create_render_pass2)( device.handle(), &create_info_vk, ptr::null(), output.as_mut_ptr(), ) - } else { + } + } else { + unsafe { (fns.khr_create_renderpass2.create_render_pass2_khr)( device.handle(), &create_info_vk, @@ -207,33 +209,35 @@ impl RenderPass { output.as_mut_ptr(), ) } - .result() - .map_err(VulkanError::from)?; + } + .result() + .map_err(VulkanError::from)?; - output.assume_init() - } else { - let create_info_fields2_vk = create_info.to_vk_fields2(); - let create_info_fields1_vk = create_info.to_vk_fields1(&create_info_fields2_vk); - let mut create_info_extensions_vk = - create_info.to_vk_extensions(&create_info_fields1_vk); - let create_info_vk = - create_info.to_vk(&create_info_fields1_vk, &mut create_info_extensions_vk); + unsafe { output.assume_init() } + } else { + let create_info_fields2_vk = create_info.to_vk_fields2(); + let create_info_fields1_vk = create_info.to_vk_fields1(&create_info_fields2_vk); + let mut create_info_extensions_vk = + create_info.to_vk_extensions(&create_info_fields1_vk); + let create_info_vk = + create_info.to_vk(&create_info_fields1_vk, &mut create_info_extensions_vk); - let fns = device.fns(); - let mut output = MaybeUninit::uninit(); + let fns = device.fns(); + let mut output = MaybeUninit::uninit(); + unsafe { (fns.v1_0.create_render_pass)( device.handle(), &create_info_vk, ptr::null(), output.as_mut_ptr(), ) - .result() - .map_err(VulkanError::from)?; - output.assume_init() } + .result() + .map_err(VulkanError::from)?; + unsafe { output.assume_init() } }; - unsafe { Ok(Self::from_handle(device, handle, create_info)) } + Ok(unsafe { Self::from_handle(device, handle, create_info) }) } /// Creates a new `RenderPass` from a raw object handle. @@ -646,10 +650,8 @@ impl RenderPass { impl Drop for RenderPass { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_render_pass)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_render_pass)(self.device.handle(), self.handle, ptr::null()) }; } } @@ -866,12 +868,10 @@ impl RenderPassCreateInfo { } = attachment; // Safety: attachment has been validated - attachment_potential_format_features[attachment_index] = unsafe { - device - .physical_device() - .format_properties_unchecked(format) - .potential_format_features() - }; + let format_properties = + unsafe { device.physical_device().format_properties_unchecked(format) }; + attachment_potential_format_features[attachment_index] = + format_properties.potential_format_features(); } if subpasses.is_empty() { diff --git a/vulkano/src/shader/mod.rs b/vulkano/src/shader/mod.rs index efba9748..6c58b3f1 100644 --- a/vulkano/src/shader/mod.rs +++ b/vulkano/src/shader/mod.rs @@ -641,10 +641,7 @@ impl ShaderModule { /// [`specialize`]: Self::specialize #[inline] pub fn entry_point(self: &Arc, name: &str) -> Option { - unsafe { - self.specialize_unchecked(HashMap::default()) - .entry_point(name) - } + unsafe { self.specialize_unchecked(HashMap::default()) }.entry_point(name) } /// Equivalent to calling [`specialize`] with empty specialization info, @@ -657,10 +654,8 @@ impl ShaderModule { name: &str, execution: ExecutionModel, ) -> Option { - unsafe { - self.specialize_unchecked(HashMap::default()) - .entry_point_with_execution(name, execution) - } + unsafe { self.specialize_unchecked(HashMap::default()) } + .entry_point_with_execution(name, execution) } /// Equivalent to calling [`specialize`] with empty specialization info, @@ -669,10 +664,7 @@ impl ShaderModule { /// [`specialize`]: Self::specialize #[inline] pub fn single_entry_point(self: &Arc) -> Option { - unsafe { - self.specialize_unchecked(HashMap::default()) - .single_entry_point() - } + unsafe { self.specialize_unchecked(HashMap::default()) }.single_entry_point() } /// Equivalent to calling [`specialize`] with empty specialization info, @@ -684,20 +676,16 @@ impl ShaderModule { self: &Arc, execution: ExecutionModel, ) -> Option { - unsafe { - self.specialize_unchecked(HashMap::default()) - .single_entry_point_with_execution(execution) - } + unsafe { self.specialize_unchecked(HashMap::default()) } + .single_entry_point_with_execution(execution) } } impl Drop for ShaderModule { #[inline] fn drop(&mut self) { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.destroy_shader_module)(self.device.handle(), self.handle, ptr::null()); - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_shader_module)(self.device.handle(), self.handle, ptr::null()) }; } } @@ -996,7 +984,7 @@ impl SpecializedShaderModule { ) -> Result, Box> { Self::validate_new(&base_module, &specialization_info)?; - unsafe { Ok(Self::new_unchecked(base_module, specialization_info)) } + Ok(unsafe { Self::new_unchecked(base_module, specialization_info) }) } fn validate_new( diff --git a/vulkano/src/swapchain/acquire_present.rs b/vulkano/src/swapchain/acquire_present.rs index 714954ec..0ae9f1f3 100644 --- a/vulkano/src/swapchain/acquire_present.rs +++ b/vulkano/src/swapchain/acquire_present.rs @@ -170,8 +170,8 @@ pub fn acquire_next_image( semaphore: Some(semaphore.clone()), fence: Some(fence.clone()), ..Default::default() - })? - }; + }) + }?; Ok(( image_index, @@ -1132,68 +1132,66 @@ where } fn flush(&self) -> Result<(), Validated> { - unsafe { - // If `flushed` already contains `true`, then `build_submission` will return `Empty`. + // SAFETY: If `flushed` already contains `true`, then `build_submission` will return + // `Empty`. + let build_submission_result = unsafe { self.build_submission() }; + self.flushed.store(true, Ordering::SeqCst); - let build_submission_result = self.build_submission(); - self.flushed.store(true, Ordering::SeqCst); + match build_submission_result? { + SubmitAnyBuilder::Empty => Ok(()), + SubmitAnyBuilder::QueuePresent(present_info) => { + let PresentInfo { + wait_semaphores: _, + swapchain_infos: swapchains, + _ne: _, + } = &present_info; - match build_submission_result? { - SubmitAnyBuilder::Empty => Ok(()), - SubmitAnyBuilder::QueuePresent(present_info) => { - let PresentInfo { - wait_semaphores: _, - swapchain_infos: swapchains, + for swapchain_info in swapchains { + let &SwapchainPresentInfo { + ref swapchain, + image_index: _, + present_id, + present_region: _, + present_mode: _, _ne: _, - } = &present_info; + } = swapchain_info; - for swapchain_info in swapchains { - let &SwapchainPresentInfo { - ref swapchain, - image_index: _, - present_id, - present_region: _, - present_mode: _, - _ne: _, - } = swapchain_info; - - if present_id.map_or(false, |present_id| { - !swapchain.try_claim_present_id(present_id) - }) { - return Err(Box::new(ValidationError { - problem: "the provided `present_id` was not greater than any \ + if present_id.map_or(false, |present_id| !unsafe { + swapchain.try_claim_present_id(present_id) + }) { + return Err(Box::new(ValidationError { + problem: "the provided `present_id` was not greater than any \ `present_id` passed previously for the same swapchain" - .into(), - vuids: &["VUID-VkPresentIdKHR-presentIds-04999"], - ..Default::default() - }) - .into()); - } + .into(), + vuids: &["VUID-VkPresentIdKHR-presentIds-04999"], + ..Default::default() + }) + .into()); } - - match self.previous.check_swapchain_image_acquired( - &self.swapchain_info.swapchain, - self.swapchain_info.image_index, - true, - ) { - Ok(_) => (), - Err(AccessCheckError::Unknown) => { - return Err(Box::new(ValidationError::from_error( - AccessError::SwapchainImageNotAcquired, - )) - .into()); - } - Err(AccessCheckError::Denied(err)) => { - return Err(Box::new(ValidationError::from_error(err)).into()); - } - } - - Ok(queue_present(&self.queue, present_info)? - .map(|r| r.map(|_| ())) - .fold(Ok(()), Result::and)?) } - _ => unreachable!(), + + match self.previous.check_swapchain_image_acquired( + &self.swapchain_info.swapchain, + self.swapchain_info.image_index, + true, + ) { + Ok(_) => (), + Err(AccessCheckError::Unknown) => { + return Err(Box::new(ValidationError::from_error( + AccessError::SwapchainImageNotAcquired, + )) + .into()); + } + Err(AccessCheckError::Denied(err)) => { + return Err(Box::new(ValidationError::from_error(err)).into()); + } + } + + Ok(unsafe { queue_present(&self.queue, present_info) }? + .map(|r| r.map(|_| ())) + .fold(Ok(()), Result::and)?) } + _ => unreachable!(), } } @@ -1288,18 +1286,16 @@ where return; } - unsafe { - if !*self.flushed.get_mut() { - // Flushing may fail, that's okay. We will still wait for the queue later, so any - // previous futures that were flushed correctly will still be waited upon. - self.flush().ok(); - } + if !*self.flushed.get_mut() { + // Flushing may fail, that's okay. We will still wait for the queue later, so any + // previous futures that were flushed correctly will still be waited upon. + self.flush().ok(); + } - if !*self.finished.get_mut() { - // Block until the queue finished. - self.queue().unwrap().with(|mut q| q.wait_idle()).unwrap(); - self.previous.signal_finished(); - } + if !*self.finished.get_mut() { + // Block until the queue finished. + self.queue().unwrap().with(|mut q| q.wait_idle()).unwrap(); + unsafe { self.previous.signal_finished() }; } } } diff --git a/vulkano/src/swapchain/mod.rs b/vulkano/src/swapchain/mod.rs index 71093689..0a456d66 100644 --- a/vulkano/src/swapchain/mod.rs +++ b/vulkano/src/swapchain/mod.rs @@ -79,14 +79,16 @@ //! # unsafe impl Sync for Window {} //! # fn build_window() -> Arc { Arc::new(Window(ptr::null())) } //! let window = build_window(); // Third-party function, not provided by vulkano -//! let _surface = unsafe { +//! let _surface = { //! let hinstance: ash::vk::HINSTANCE = 0; // Windows-specific object -//! Surface::from_win32( -//! instance.clone(), -//! hinstance, -//! window.hwnd() as ash::vk::HWND, -//! Some(window), -//! ) +//! unsafe { +//! Surface::from_win32( +//! instance.clone(), +//! hinstance, +//! window.hwnd() as ash::vk::HWND, +//! Some(window), +//! ) +//! } //! .unwrap() //! }; //! ``` @@ -416,7 +418,7 @@ impl Swapchain { ) -> Result<(Arc, Vec>), Validated> { Self::validate_new_inner(&device, &surface, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, surface, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, surface, create_info) }?) } #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] @@ -469,7 +471,7 @@ impl Swapchain { } } - unsafe { Ok(self.recreate_unchecked(create_info)?) } + Ok(unsafe { self.recreate_unchecked(create_info) }?) } #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] @@ -488,8 +490,8 @@ impl Swapchain { *self.is_retired.lock() = true; let (handle, image_handles) = unsafe { - Self::new_inner_unchecked(&self.device, &self.surface, &create_info, Some(self))? - }; + Self::new_inner_unchecked(&self.device, &self.surface, &create_info, Some(self)) + }?; let (swapchain, swapchain_images) = Self::from_handle( self.device.clone(), @@ -552,16 +554,14 @@ impl Swapchain { assert_eq!(device.instance(), surface.instance()); // VUID-VkSwapchainCreateInfoKHR-surface-01270 - if !device - .active_queue_family_indices() - .iter() - .any(|&index| unsafe { + if !device.active_queue_family_indices().iter().any(|&index| { + unsafe { device .physical_device() .surface_support_unchecked(index, surface) - .unwrap_or_default() - }) - { + } + .unwrap_or_default() + }) { return Err(Box::new(ValidationError { context: "surface".into(), problem: "is not supported by the physical device".into(), @@ -571,82 +571,74 @@ impl Swapchain { } let surface_capabilities = unsafe { - device - .physical_device() - .surface_capabilities_unchecked( - surface, - SurfaceInfo { - present_mode: device - .enabled_extensions() - .ext_swapchain_maintenance1 - .then_some(present_mode), - full_screen_exclusive, - win32_monitor: win32_monitor - .filter(|_| full_screen_exclusive != FullScreenExclusive::Default), - ..Default::default() - }, - ) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::surface_capabilities` \ + device.physical_device().surface_capabilities_unchecked( + surface, + SurfaceInfo { + present_mode: device + .enabled_extensions() + .ext_swapchain_maintenance1 + .then_some(present_mode), + full_screen_exclusive, + win32_monitor: win32_monitor + .filter(|_| full_screen_exclusive != FullScreenExclusive::Default), + ..Default::default() + }, + ) + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::surface_capabilities` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; let surface_formats = unsafe { - device - .physical_device() - .surface_formats_unchecked( - surface, - SurfaceInfo { - present_mode: device - .enabled_extensions() - .ext_swapchain_maintenance1 - .then_some(present_mode), - full_screen_exclusive, - win32_monitor: win32_monitor.filter(|_| { - surface.api() == SurfaceApi::Win32 - && full_screen_exclusive - == FullScreenExclusive::ApplicationControlled - }), - ..Default::default() - }, - ) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::surface_formats` \ + device.physical_device().surface_formats_unchecked( + surface, + SurfaceInfo { + present_mode: device + .enabled_extensions() + .ext_swapchain_maintenance1 + .then_some(present_mode), + full_screen_exclusive, + win32_monitor: win32_monitor.filter(|_| { + surface.api() == SurfaceApi::Win32 + && full_screen_exclusive == FullScreenExclusive::ApplicationControlled + }), + ..Default::default() + }, + ) + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::surface_formats` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; let surface_present_modes = unsafe { - device - .physical_device() - .surface_present_modes_unchecked( - surface, - SurfaceInfo { - full_screen_exclusive, - win32_monitor: win32_monitor.filter(|_| { - surface.api() == SurfaceApi::Win32 - && full_screen_exclusive - == FullScreenExclusive::ApplicationControlled - }), - ..Default::default() - }, - ) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::surface_present_modes` \ + device.physical_device().surface_present_modes_unchecked( + surface, + SurfaceInfo { + full_screen_exclusive, + win32_monitor: win32_monitor.filter(|_| { + surface.api() == SurfaceApi::Win32 + && full_screen_exclusive == FullScreenExclusive::ApplicationControlled + }), + ..Default::default() + }, + ) + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::surface_present_modes` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; if surface_capabilities .max_image_count @@ -825,26 +817,24 @@ impl Swapchain { if scaling_behavior.is_some() || present_gravity.is_some() { let surface_capabilities = unsafe { - device - .physical_device() - .surface_capabilities_unchecked( - surface, - SurfaceInfo { - present_mode: Some(present_mode), - full_screen_exclusive, - win32_monitor, - ..Default::default() - }, - ) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::surface_capabilities` \ + device.physical_device().surface_capabilities_unchecked( + surface, + SurfaceInfo { + present_mode: Some(present_mode), + full_screen_exclusive, + win32_monitor, + ..Default::default() + }, + ) + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::surface_capabilities` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; if let Some(scaling_behavior) = scaling_behavior { if !surface_capabilities @@ -1112,12 +1102,10 @@ impl Swapchain { .images .iter() .enumerate() - .map(|(image_index, entry)| unsafe { - Ok(Arc::new(Image::from_swapchain( - entry.handle, - swapchain.clone(), - image_index as u32, - )?)) + .map(|(image_index, entry)| { + Ok(Arc::new(unsafe { + Image::from_swapchain(entry.handle, swapchain.clone(), image_index as u32) + }?)) }) .collect::>()?; @@ -1401,7 +1389,7 @@ impl Swapchain { let is_retired_lock = self.is_retired.lock(); self.validate_wait_for_present(present_id, timeout, *is_retired_lock)?; - unsafe { Ok(self.wait_for_present_unchecked(present_id, timeout)?) } + Ok(unsafe { self.wait_for_present_unchecked(present_id, timeout) }?) } fn validate_wait_for_present( @@ -1486,7 +1474,7 @@ impl Swapchain { pub fn acquire_full_screen_exclusive_mode(&self) -> Result<(), Validated> { self.validate_acquire_full_screen_exclusive_mode()?; - unsafe { Ok(self.acquire_full_screen_exclusive_mode_unchecked()?) } + Ok(unsafe { self.acquire_full_screen_exclusive_mode_unchecked() }?) } fn validate_acquire_full_screen_exclusive_mode(&self) -> Result<(), Box> { @@ -1544,7 +1532,7 @@ impl Swapchain { pub fn release_full_screen_exclusive_mode(&self) -> Result<(), Validated> { self.validate_release_full_screen_exclusive_mode()?; - unsafe { Ok(self.release_full_screen_exclusive_mode_unchecked()?) } + Ok(unsafe { self.release_full_screen_exclusive_mode_unchecked() }?) } fn validate_release_full_screen_exclusive_mode(&self) -> Result<(), Box> { @@ -1632,14 +1620,14 @@ impl Swapchain { impl Drop for Swapchain { #[inline] fn drop(&mut self) { + let fns = self.device.fns(); unsafe { - let fns = self.device.fns(); (fns.khr_swapchain.destroy_swapchain_khr)( self.device.handle(), self.handle, ptr::null(), - ); - } + ) + }; } } @@ -1982,15 +1970,15 @@ impl SwapchainCreateInfo { usage: image_usage, ..Default::default() }) - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::image_format_properties` \ + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::image_format_properties` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; if image_format_properties.is_none() { return Err(Box::new(ValidationError { diff --git a/vulkano/src/swapchain/surface.rs b/vulkano/src/swapchain/surface.rs index ee3301d6..21d04f98 100644 --- a/vulkano/src/swapchain/surface.rs +++ b/vulkano/src/swapchain/surface.rs @@ -188,7 +188,7 @@ impl Surface { ) -> Result, Validated> { Self::validate_headless(&instance)?; - unsafe { Ok(Self::headless_unchecked(instance, object)?) } + Ok(unsafe { Self::headless_unchecked(instance, object) }?) } fn validate_headless(instance: &Instance) -> Result<(), Box> { @@ -242,12 +242,7 @@ impl Surface { ) -> Result, Validated> { Self::validate_from_display_plane(&display_mode, &create_info)?; - unsafe { - Ok(Self::from_display_plane_unchecked( - display_mode, - create_info, - )?) - } + Ok(unsafe { Self::from_display_plane_unchecked(display_mode, create_info) }?) } fn validate_from_display_plane( @@ -283,15 +278,15 @@ impl Surface { .display() .physical_device() .display_plane_properties_raw() - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::display_plane_properties` \ + } + .map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::display_plane_properties` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; if display_mode.display().plane_reorder_possible() { if plane_stack_index as usize >= display_plane_properties_raw.len() { @@ -318,18 +313,17 @@ impl Surface { } } - let display_plane_capabilities = unsafe { - display_mode - .display_plane_capabilities_unchecked(plane_index) - .map_err(|_err| { + let display_plane_capabilities = + unsafe { display_mode.display_plane_capabilities_unchecked(plane_index) }.map_err( + |_err| { Box::new(ValidationError { problem: "`DisplayMode::display_plane_capabilities` \ returned an error" .into(), ..Default::default() }) - })? - }; + }, + )?; if !display_plane_capabilities .supported_alpha @@ -1393,10 +1387,10 @@ impl Surface { impl Drop for Surface { #[inline] fn drop(&mut self) { + let fns = self.instance.fns(); unsafe { - let fns = self.instance.fns(); - (fns.khr_surface.destroy_surface_khr)(self.instance.handle(), self.handle, ptr::null()); - } + (fns.khr_surface.destroy_surface_khr)(self.instance.handle(), self.handle, ptr::null()) + }; } } @@ -1525,18 +1519,15 @@ impl DisplaySurfaceCreateInfo { .set_vuids(&["VUID-VkDisplaySurfaceCreateInfoKHR-alphaMode-parameter"]) })?; - let display_plane_properties_raw = unsafe { - physical_device - .display_plane_properties_raw() - .map_err(|_err| { - Box::new(ValidationError { - problem: "`PhysicalDevice::display_plane_properties` \ + let display_plane_properties_raw = + unsafe { physical_device.display_plane_properties_raw() }.map_err(|_err| { + Box::new(ValidationError { + problem: "`PhysicalDevice::display_plane_properties` \ returned an error" - .into(), - ..Default::default() - }) - })? - }; + .into(), + ..Default::default() + }) + })?; if plane_index as usize >= display_plane_properties_raw.len() { return Err(Box::new(ValidationError { diff --git a/vulkano/src/sync/event.rs b/vulkano/src/sync/event.rs index 2423725a..4798eecf 100644 --- a/vulkano/src/sync/event.rs +++ b/vulkano/src/sync/event.rs @@ -54,7 +54,7 @@ impl Event { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -86,18 +86,20 @@ impl Event { ) -> Result { let create_info_vk = create_info.to_vk(); - let handle = unsafe { + let handle = { let mut output = MaybeUninit::uninit(); let fns = device.fns(); - (fns.v1_0.create_event)( - device.handle(), - &create_info_vk, - ptr::null(), - output.as_mut_ptr(), - ) + unsafe { + (fns.v1_0.create_event)( + device.handle(), + &create_info_vk, + ptr::null(), + output.as_mut_ptr(), + ) + } .result() .map_err(VulkanError::from)?; - output.assume_init() + unsafe { output.assume_init() } }; Ok(Self::from_handle(device, handle, create_info)) @@ -114,13 +116,14 @@ impl Event { let handle = device.event_pool().lock().pop(); let event = match handle { Some(handle) => { + // Make sure the event isn't signaled + let fns = device.fns(); unsafe { - // Make sure the event isn't signaled - let fns = device.fns(); (fns.v1_0.reset_event)(device.handle(), handle) .result() - .map_err(VulkanError::from)?; - } + .map_err(VulkanError::from) + }?; + Event { handle, device: InstanceOwnedDebugWrapper(device), @@ -132,7 +135,7 @@ impl Event { } None => { // Pool is empty, alloc new event - let mut event = unsafe { Event::new_unchecked(device, Default::default())? }; + let mut event = unsafe { Event::new_unchecked(device, Default::default()) }?; event.must_put_in_pool = true; event } @@ -175,7 +178,7 @@ impl Event { pub fn is_signaled(&self) -> Result> { self.validate_is_signaled()?; - unsafe { Ok(self.is_signaled_unchecked()?) } + Ok(unsafe { self.is_signaled_unchecked() }?) } fn validate_is_signaled(&self) -> Result<(), Box> { @@ -185,14 +188,12 @@ impl Event { #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] #[inline] pub unsafe fn is_signaled_unchecked(&self) -> Result { - unsafe { - let fns = self.device.fns(); - let result = (fns.v1_0.get_event_status)(self.device.handle(), self.handle); - match result { - ash::vk::Result::EVENT_SET => Ok(true), - ash::vk::Result::EVENT_RESET => Ok(false), - err => Err(VulkanError::from(err)), - } + let fns = self.device.fns(); + let result = unsafe { (fns.v1_0.get_event_status)(self.device.handle(), self.handle) }; + match result { + ash::vk::Result::EVENT_SET => Ok(true), + ash::vk::Result::EVENT_RESET => Ok(false), + err => Err(VulkanError::from(err)), } } @@ -202,7 +203,7 @@ impl Event { pub fn set(&mut self) -> Result<(), Validated> { self.validate_set()?; - unsafe { Ok(self.set_unchecked()?) } + Ok(unsafe { self.set_unchecked() }?) } fn validate_set(&mut self) -> Result<(), Box> { @@ -212,13 +213,11 @@ impl Event { #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] #[inline] pub unsafe fn set_unchecked(&mut self) -> Result<(), VulkanError> { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.set_event)(self.device.handle(), self.handle) - .result() - .map_err(VulkanError::from)?; - Ok(()) - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.set_event)(self.device.handle(), self.handle) } + .result() + .map_err(VulkanError::from)?; + Ok(()) } /// Changes the `Event` to the unsignaled state. @@ -247,27 +246,23 @@ impl Event { #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))] #[inline] pub unsafe fn reset_unchecked(&mut self) -> Result<(), VulkanError> { - unsafe { - let fns = self.device.fns(); - (fns.v1_0.reset_event)(self.device.handle(), self.handle) - .result() - .map_err(VulkanError::from)?; - Ok(()) - } + let fns = self.device.fns(); + unsafe { (fns.v1_0.reset_event)(self.device.handle(), self.handle) } + .result() + .map_err(VulkanError::from)?; + Ok(()) } } impl Drop for Event { #[inline] fn drop(&mut self) { - unsafe { - if self.must_put_in_pool { - let raw_event = self.handle; - self.device.event_pool().lock().push(raw_event); - } else { - let fns = self.device.fns(); - (fns.v1_0.destroy_event)(self.device.handle(), self.handle, ptr::null()); - } + if self.must_put_in_pool { + let raw_event = self.handle; + self.device.event_pool().lock().push(raw_event); + } else { + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_event)(self.device.handle(), self.handle, ptr::null()) }; } } } diff --git a/vulkano/src/sync/fence.rs b/vulkano/src/sync/fence.rs index bf4a5453..3fc4e723 100644 --- a/vulkano/src/sync/fence.rs +++ b/vulkano/src/sync/fence.rs @@ -68,7 +68,7 @@ impl Fence { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -119,13 +119,11 @@ impl Fence { let handle = device.fence_pool().lock().pop(); let fence = match handle { Some(handle) => { - unsafe { - // Make sure the fence isn't signaled - let fns = device.fns(); - (fns.v1_0.reset_fences)(device.handle(), 1, &handle) - .result() - .map_err(VulkanError::from)?; - } + // Make sure the fence isn't signaled + let fns = device.fns(); + unsafe { (fns.v1_0.reset_fences)(device.handle(), 1, &handle) } + .result() + .map_err(VulkanError::from)?; Fence { handle, @@ -141,7 +139,7 @@ impl Fence { None => { // Pool is empty, alloc new fence let mut fence = - unsafe { Fence::new_unchecked(device, FenceCreateInfo::default())? }; + unsafe { Fence::new_unchecked(device, FenceCreateInfo::default()) }?; fence.must_put_in_pool = true; fence } @@ -195,11 +193,8 @@ impl Fence { /// Returns true if the fence is signaled. #[inline] pub fn is_signaled(&self) -> Result { - let result = unsafe { - let fns = self.device.fns(); - (fns.v1_0.get_fence_status)(self.device.handle(), self.handle) - }; - + let fns = self.device.fns(); + let result = unsafe { (fns.v1_0.get_fence_status)(self.device.handle(), self.handle) }; match result { ash::vk::Result::SUCCESS => Ok(true), ash::vk::Result::NOT_READY => Ok(false), @@ -218,8 +213,8 @@ impl Fence { .saturating_add(timeout.subsec_nanos() as u64) }); + let fns = self.device.fns(); let result = unsafe { - let fns = self.device.fns(); (fns.v1_0.wait_for_fences)( self.device.handle(), 1, @@ -247,7 +242,7 @@ impl Fence { let fences: SmallVec<[_; 8]> = fences.into_iter().collect(); Self::validate_multi_wait(&fences, timeout)?; - unsafe { Ok(Self::multi_wait_unchecked(fences, timeout)?) } + Ok(unsafe { Self::multi_wait_unchecked(fences, timeout) }?) } fn validate_multi_wait( @@ -322,7 +317,7 @@ impl Fence { pub unsafe fn reset(&self) -> Result<(), Validated> { self.validate_reset()?; - unsafe { Ok(self.reset_unchecked()?) } + Ok(unsafe { self.reset_unchecked() }?) } fn validate_reset(&self) -> Result<(), Box> { @@ -350,7 +345,7 @@ impl Fence { let fences: SmallVec<[_; 8]> = fences.into_iter().collect(); Self::validate_multi_reset(&fences)?; - unsafe { Ok(Self::multi_reset_unchecked(fences)?) } + Ok(unsafe { Self::multi_reset_unchecked(fences) }?) } fn validate_multi_reset(fences: &[&Fence]) -> Result<(), Box> { @@ -408,7 +403,7 @@ impl Fence { ) -> Result> { self.validate_export_fd(handle_type)?; - unsafe { Ok(self.export_fd_unchecked(handle_type)?) } + Ok(unsafe { self.export_fd_unchecked(handle_type) }?) } fn validate_export_fd( @@ -507,7 +502,7 @@ impl Fence { ) -> Result> { self.validate_export_win32_handle(handle_type)?; - unsafe { Ok(self.export_win32_handle_unchecked(handle_type)?) } + Ok(unsafe { self.export_win32_handle_unchecked(handle_type) }?) } fn validate_export_win32_handle( @@ -715,14 +710,12 @@ impl Fence { impl Drop for Fence { #[inline] fn drop(&mut self) { - unsafe { - if self.must_put_in_pool { - let raw_fence = self.handle; - self.device.fence_pool().lock().push(raw_fence); - } else { - let fns = self.device.fns(); - (fns.v1_0.destroy_fence)(self.device.handle(), self.handle, ptr::null()); - } + if self.must_put_in_pool { + let raw_fence = self.handle; + self.device.fence_pool().lock().push(raw_fence); + } else { + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_fence)(self.device.handle(), self.handle, ptr::null()) }; } } } @@ -1337,9 +1330,7 @@ mod tests { ) .unwrap(); - unsafe { - fence.reset().unwrap(); - } + unsafe { fence.reset() }.unwrap(); assert!(!fence.is_signaled().unwrap()); } diff --git a/vulkano/src/sync/future/fence_signal.rs b/vulkano/src/sync/future/fence_signal.rs index ccf5fb52..bb114bd0 100644 --- a/vulkano/src/sync/future/fence_signal.rs +++ b/vulkano/src/sync/future/fence_signal.rs @@ -159,9 +159,7 @@ where match replace(&mut *state, FenceSignalFutureState::Cleaned) { FenceSignalFutureState::Flushed(previous, fence) => { fence.wait(timeout)?; - unsafe { - previous.signal_finished(); - } + unsafe { previous.signal_finished() }; Ok(()) } FenceSignalFutureState::Cleaned => Ok(()), @@ -182,7 +180,7 @@ where match *state { FenceSignalFutureState::Flushed(ref mut prev, ref fence) => { if fence.wait(Some(Duration::from_secs(0))).is_ok() { - unsafe { prev.signal_finished() } + unsafe { prev.signal_finished() }; *state = FenceSignalFutureState::Cleaned; } else { prev.cleanup_finished(); @@ -203,48 +201,50 @@ where &self, state: &mut MutexGuard<'_, FenceSignalFutureState>, ) -> Result<(), Validated> { - unsafe { - // In this function we temporarily replace the current state with `Poisoned` at the - // beginning, and we take care to always put back a value into `state` before - // returning (even in case of error). - let old_state = replace(&mut **state, FenceSignalFutureState::Poisoned); + // In this function we temporarily replace the current state with `Poisoned` at the + // beginning, and we take care to always put back a value into `state` before + // returning (even in case of error). + let old_state = replace(&mut **state, FenceSignalFutureState::Poisoned); - let (previous, new_fence, partially_flushed) = match old_state { - FenceSignalFutureState::Pending(prev, fence) => (prev, fence, false), - FenceSignalFutureState::PartiallyFlushed(prev, fence) => (prev, fence, true), - other => { - // We were already flushed in the past, or we're already poisoned. Don't do - // anything. - **state = other; - return Ok(()); - } - }; - - // TODO: meh for unwrap - let queue = previous.queue().unwrap(); - - // There are three possible outcomes for the flush operation: success, partial success - // in which case `result` will contain `Err(OutcomeErr::Partial)`, or total failure - // in which case `result` will contain `Err(OutcomeErr::Full)`. - enum OutcomeErr { - Partial(E), - Full(E), + let (previous, new_fence, partially_flushed) = match old_state { + FenceSignalFutureState::Pending(prev, fence) => (prev, fence, false), + FenceSignalFutureState::PartiallyFlushed(prev, fence) => (prev, fence, true), + other => { + // We were already flushed in the past, or we're already poisoned. Don't do + // anything. + **state = other; + return Ok(()); } - let result = match previous.build_submission()? { - SubmitAnyBuilder::Empty => { - debug_assert!(!partially_flushed); + }; + // TODO: meh for unwrap + let queue = previous.queue().unwrap(); + + // There are three possible outcomes for the flush operation: success, partial success + // in which case `result` will contain `Err(OutcomeErr::Partial)`, or total failure + // in which case `result` will contain `Err(OutcomeErr::Full)`. + enum OutcomeErr { + Partial(E), + Full(E), + } + let result = match unsafe { previous.build_submission() }? { + SubmitAnyBuilder::Empty => { + debug_assert!(!partially_flushed); + + unsafe { queue_submit( &queue, Default::default(), Some(new_fence.clone()), &previous, ) - .map_err(OutcomeErr::Full) } - SubmitAnyBuilder::SemaphoresWait(semaphores) => { - debug_assert!(!partially_flushed); + .map_err(OutcomeErr::Full) + } + SubmitAnyBuilder::SemaphoresWait(semaphores) => { + debug_assert!(!partially_flushed); + unsafe { queue_submit( &queue, SubmitInfo { @@ -263,106 +263,113 @@ where None, &previous, ) + } + .map_err(OutcomeErr::Full) + } + SubmitAnyBuilder::CommandBuffer(submit_info, fence) => { + debug_assert!(!partially_flushed); + // The assert below could technically be a debug assertion as it is part of the + // safety contract of the trait. However it is easy to get this wrong if you + // write a custom implementation, and if so the consequences would be + // disastrous and hard to debug. Therefore we prefer to just use a regular + // assertion. + assert!(fence.is_none()); + + unsafe { queue_submit(&queue, submit_info, Some(new_fence.clone()), &previous) } .map_err(OutcomeErr::Full) - } - SubmitAnyBuilder::CommandBuffer(submit_info, fence) => { - debug_assert!(!partially_flushed); - // The assert below could technically be a debug assertion as it is part of the - // safety contract of the trait. However it is easy to get this wrong if you - // write a custom implementation, and if so the consequences would be - // disastrous and hard to debug. Therefore we prefer to just use a regular - // assertion. - assert!(fence.is_none()); + } + SubmitAnyBuilder::BindSparse(bind_infos, fence) => { + debug_assert!(!partially_flushed); + // Same remark as `CommandBuffer`. + assert!(fence.is_none()); + debug_assert!(queue.device().physical_device().queue_family_properties() + [queue.queue_family_index() as usize] + .queue_flags + .intersects(QueueFlags::SPARSE_BINDING)); - queue_submit(&queue, submit_info, Some(new_fence.clone()), &previous) - .map_err(OutcomeErr::Full) - } - SubmitAnyBuilder::BindSparse(bind_infos, fence) => { - debug_assert!(!partially_flushed); - // Same remark as `CommandBuffer`. - assert!(fence.is_none()); - debug_assert!(queue.device().physical_device().queue_family_properties() - [queue.queue_family_index() as usize] - .queue_flags - .intersects(QueueFlags::SPARSE_BINDING)); - - queue_bind_sparse(&queue, bind_infos, Some(new_fence.clone())) - .map_err(OutcomeErr::Full) - } - SubmitAnyBuilder::QueuePresent(present_info) => { - if partially_flushed { + unsafe { queue_bind_sparse(&queue, bind_infos, Some(new_fence.clone())) } + .map_err(OutcomeErr::Full) + } + SubmitAnyBuilder::QueuePresent(present_info) => { + if partially_flushed { + unsafe { queue_submit( &queue, Default::default(), Some(new_fence.clone()), &previous, ) - .map_err(OutcomeErr::Partial) - } else { - for swapchain_info in &present_info.swapchain_infos { - if swapchain_info.present_id.map_or(false, |present_id| { - !swapchain_info.swapchain.try_claim_present_id(present_id) - }) { - return Err(Box::new(ValidationError { - problem: "the provided `present_id` was not greater than any \ + } + .map_err(OutcomeErr::Partial) + } else { + for swapchain_info in &present_info.swapchain_infos { + if swapchain_info + .present_id + .map_or(false, |present_id| !unsafe { + swapchain_info.swapchain.try_claim_present_id(present_id) + }) + { + return Err(Box::new(ValidationError { + problem: "the provided `present_id` was not greater than any \ `present_id` passed previously for the same swapchain" - .into(), - vuids: &["VUID-VkPresentIdKHR-presentIds-04999"], - ..Default::default() - }) - .into()); - } - - match previous.check_swapchain_image_acquired( - &swapchain_info.swapchain, - swapchain_info.image_index, - true, - ) { - Ok(_) => (), - Err(AccessCheckError::Unknown) => { - return Err(Box::new(ValidationError::from_error( - AccessError::SwapchainImageNotAcquired, - )) - .into()); - } - Err(AccessCheckError::Denied(err)) => { - return Err(Box::new(ValidationError::from_error(err)).into()); - } - } + .into(), + vuids: &["VUID-VkPresentIdKHR-presentIds-04999"], + ..Default::default() + }) + .into()); } - let intermediary_result = queue_present(&queue, present_info)? - .map(|r| r.map(|_| ())) - .fold(Ok(()), Result::and); + match previous.check_swapchain_image_acquired( + &swapchain_info.swapchain, + swapchain_info.image_index, + true, + ) { + Ok(_) => (), + Err(AccessCheckError::Unknown) => { + return Err(Box::new(ValidationError::from_error( + AccessError::SwapchainImageNotAcquired, + )) + .into()); + } + Err(AccessCheckError::Denied(err)) => { + return Err(Box::new(ValidationError::from_error(err)).into()); + } + } + } - match intermediary_result { - Ok(()) => queue_submit( + let intermediary_result = unsafe { queue_present(&queue, present_info) }? + .map(|r| r.map(|_| ())) + .fold(Ok(()), Result::and); + + match intermediary_result { + Ok(()) => unsafe { + queue_submit( &queue, Default::default(), Some(new_fence.clone()), &previous, ) - .map_err(OutcomeErr::Partial), - Err(err) => Err(OutcomeErr::Full(err.into())), } + .map_err(OutcomeErr::Partial), + Err(err) => Err(OutcomeErr::Full(err.into())), } } - }; + } + }; - // Restore the state before returning. - match result { - Ok(()) => { - **state = FenceSignalFutureState::Flushed(previous, new_fence); - Ok(()) - } - Err(OutcomeErr::Partial(err)) => { - **state = FenceSignalFutureState::PartiallyFlushed(previous, new_fence); - Err(err) - } - Err(OutcomeErr::Full(err)) => { - **state = FenceSignalFutureState::Pending(previous, new_fence); - Err(err) - } + // Restore the state before returning. + match result { + Ok(()) => { + **state = FenceSignalFutureState::Flushed(previous, new_fence); + Ok(()) + } + Err(OutcomeErr::Partial(err)) => { + **state = FenceSignalFutureState::PartiallyFlushed(previous, new_fence); + Err(err) + } + Err(OutcomeErr::Full(err)) => { + **state = FenceSignalFutureState::Pending(previous, new_fence); + Err(err) } } } @@ -536,9 +543,7 @@ where // This is a normal situation. Submitting worked. // TODO: handle errors? fence.wait(None).unwrap(); - unsafe { - previous.signal_finished(); - } + unsafe { previous.signal_finished() }; } FenceSignalFutureState::Cleaned => { // Also a normal situation. The user called `cleanup_finished()` before dropping. diff --git a/vulkano/src/sync/future/semaphore_signal.rs b/vulkano/src/sync/future/semaphore_signal.rs index 06078271..d6a53f77 100644 --- a/vulkano/src/sync/future/semaphore_signal.rs +++ b/vulkano/src/sync/future/semaphore_signal.rs @@ -73,17 +73,17 @@ where } fn flush(&self) -> Result<(), Validated> { - unsafe { - let mut wait_submitted = self.wait_submitted.lock(); + let mut wait_submitted = self.wait_submitted.lock(); - if *wait_submitted { - return Ok(()); - } + if *wait_submitted { + return Ok(()); + } - let queue = self.previous.queue().unwrap(); + let queue = self.previous.queue().unwrap(); - match self.previous.build_submission()? { - SubmitAnyBuilder::Empty => { + match unsafe { self.previous.build_submission() }? { + SubmitAnyBuilder::Empty => { + unsafe { queue_submit( &queue, SubmitInfo { @@ -94,9 +94,11 @@ where }, None, &self.previous, - )?; - } - SubmitAnyBuilder::SemaphoresWait(semaphores) => { + ) + }?; + } + SubmitAnyBuilder::SemaphoresWait(semaphores) => { + unsafe { queue_submit( &queue, SubmitInfo { @@ -117,62 +119,67 @@ where }, None, &self.previous, - )?; - } - SubmitAnyBuilder::CommandBuffer(mut submit_info, fence) => { - debug_assert!(submit_info.signal_semaphores.is_empty()); + ) + }?; + } + SubmitAnyBuilder::CommandBuffer(mut submit_info, fence) => { + debug_assert!(submit_info.signal_semaphores.is_empty()); - submit_info - .signal_semaphores - .push(SemaphoreSubmitInfo::new(self.semaphore.clone())); + submit_info + .signal_semaphores + .push(SemaphoreSubmitInfo::new(self.semaphore.clone())); - queue_submit(&queue, submit_info, fence, &self.previous)?; - } - SubmitAnyBuilder::BindSparse(_, _) => { - unimplemented!() // TODO: how to do that? - /*debug_assert_eq!(builder.num_signal_semaphores(), 0); - builder.add_signal_semaphore(&self.semaphore); - builder.submit(&queue)?;*/ - } - SubmitAnyBuilder::QueuePresent(present_info) => { - for swapchain_info in &present_info.swapchain_infos { - if swapchain_info.present_id.map_or(false, |present_id| { - !swapchain_info.swapchain.try_claim_present_id(present_id) - }) { - return Err(Box::new(ValidationError { - problem: "the provided `present_id` was not greater than any \ + unsafe { queue_submit(&queue, submit_info, fence, &self.previous) }?; + } + SubmitAnyBuilder::BindSparse(_, _) => { + unimplemented!() // TODO: how to do that? + /*debug_assert_eq!(builder.num_signal_semaphores(), 0); + builder.add_signal_semaphore(&self.semaphore); + builder.submit(&queue)?;*/ + } + SubmitAnyBuilder::QueuePresent(present_info) => { + for swapchain_info in &present_info.swapchain_infos { + if swapchain_info + .present_id + .map_or(false, |present_id| !unsafe { + swapchain_info.swapchain.try_claim_present_id(present_id) + }) + { + return Err(Box::new(ValidationError { + problem: "the provided `present_id` was not greater than any \ `present_id` passed previously for the same swapchain" - .into(), - vuids: &["VUID-VkPresentIdKHR-presentIds-04999"], - ..Default::default() - }) - .into()); - } - - match self.previous.check_swapchain_image_acquired( - &swapchain_info.swapchain, - swapchain_info.image_index, - true, - ) { - Ok(_) => (), - Err(AccessCheckError::Unknown) => { - return Err(Box::new(ValidationError::from_error( - AccessError::SwapchainImageNotAcquired, - )) - .into()); - } - Err(AccessCheckError::Denied(err)) => { - return Err(Box::new(ValidationError::from_error(err)).into()); - } - } + .into(), + vuids: &["VUID-VkPresentIdKHR-presentIds-04999"], + ..Default::default() + }) + .into()); } - queue_present(&queue, present_info)? - .map(|r| r.map(|_| ())) - .fold(Ok(()), Result::and)?; + match self.previous.check_swapchain_image_acquired( + &swapchain_info.swapchain, + swapchain_info.image_index, + true, + ) { + Ok(_) => (), + Err(AccessCheckError::Unknown) => { + return Err(Box::new(ValidationError::from_error( + AccessError::SwapchainImageNotAcquired, + )) + .into()); + } + Err(AccessCheckError::Denied(err)) => { + return Err(Box::new(ValidationError::from_error(err)).into()); + } + } + } - // FIXME: problematic because if we return an error and flush() is called again, - // then we'll submit the present twice + unsafe { queue_present(&queue, present_info) }? + .map(|r| r.map(|_| ())) + .fold(Ok(()), Result::and)?; + + // FIXME: problematic because if we return an error and flush() is called again, + // then we'll submit the present twice + unsafe { queue_submit( &queue, SubmitInfo { @@ -183,14 +190,14 @@ where }, None, &self.previous, - )?; - } - }; + ) + }?; + } + }; - // Only write `true` here in order to try again next time if an error occurs. - *wait_submitted = true; - Ok(()) - } + // Only write `true` here in order to try again next time if an error occurs. + *wait_submitted = true; + Ok(()) } unsafe fn signal_finished(&self) { @@ -262,9 +269,7 @@ where // Block until the queue finished. self.queue().unwrap().with(|mut q| q.wait_idle()).unwrap(); - unsafe { - self.signal_finished(); - } + unsafe { self.signal_finished() }; } } } diff --git a/vulkano/src/sync/semaphore.rs b/vulkano/src/sync/semaphore.rs index 07d1464c..210b30ca 100644 --- a/vulkano/src/sync/semaphore.rs +++ b/vulkano/src/sync/semaphore.rs @@ -100,7 +100,7 @@ impl Semaphore { ) -> Result> { Self::validate_new(&device, &create_info)?; - unsafe { Ok(Self::new_unchecked(device, create_info)?) } + Ok(unsafe { Self::new_unchecked(device, create_info) }?) } fn validate_new( @@ -162,7 +162,7 @@ impl Semaphore { None => { // Pool is empty, alloc new semaphore let mut semaphore = - unsafe { Semaphore::new_unchecked(device, Default::default())? }; + unsafe { Semaphore::new_unchecked(device, Default::default()) }?; semaphore.must_put_in_pool = true; semaphore } @@ -222,7 +222,7 @@ impl Semaphore { pub fn counter_value(&self) -> Result> { self.validate_counter_value()?; - unsafe { Ok(self.counter_value_unchecked()?) } + Ok(unsafe { self.counter_value_unchecked() }?) } fn validate_counter_value(&self) -> Result<(), Box> { @@ -330,7 +330,7 @@ impl Semaphore { ) -> Result<(), Validated> { self.validate_wait(&wait_info, timeout)?; - unsafe { Ok(self.wait_unchecked(wait_info, timeout)?) } + Ok(unsafe { self.wait_unchecked(wait_info, timeout) }?) } fn validate_wait( @@ -407,7 +407,7 @@ impl Semaphore { ) -> Result<(), Validated> { Self::validate_wait_multiple(&wait_info, timeout)?; - unsafe { Ok(Self::wait_multiple_unchecked(wait_info, timeout)?) } + Ok(unsafe { Self::wait_multiple_unchecked(wait_info, timeout) }?) } fn validate_wait_multiple( @@ -489,7 +489,7 @@ impl Semaphore { ) -> Result> { self.validate_export_fd(handle_type)?; - unsafe { Ok(self.export_fd_unchecked(handle_type)?) } + Ok(unsafe { self.export_fd_unchecked(handle_type) }?) } fn validate_export_fd( @@ -600,7 +600,7 @@ impl Semaphore { ) -> Result> { self.validate_export_win32_handle(handle_type)?; - unsafe { Ok(self.export_win32_handle_unchecked(handle_type)?) } + Ok(unsafe { self.export_win32_handle_unchecked(handle_type) }?) } fn validate_export_win32_handle( @@ -691,7 +691,7 @@ impl Semaphore { ) -> Result> { self.validate_export_zircon_handle(handle_type)?; - unsafe { Ok(self.export_zircon_handle_unchecked(handle_type)?) } + Ok(unsafe { self.export_zircon_handle_unchecked(handle_type) }?) } fn validate_export_zircon_handle( @@ -989,14 +989,12 @@ impl Semaphore { impl Drop for Semaphore { #[inline] fn drop(&mut self) { - unsafe { - if self.must_put_in_pool { - let raw_sem = self.handle; - self.device.semaphore_pool().lock().push(raw_sem); - } else { - let fns = self.device.fns(); - (fns.v1_0.destroy_semaphore)(self.device.handle(), self.handle, ptr::null()); - } + if self.must_put_in_pool { + let raw_sem = self.handle; + self.device.semaphore_pool().lock().push(raw_sem); + } else { + let fns = self.device.fns(); + unsafe { (fns.v1_0.destroy_semaphore)(self.device.handle(), self.handle, ptr::null()) }; } } } @@ -2169,9 +2167,6 @@ mod tests { }, ) .unwrap(); - let _fd = unsafe { - sem.export_fd(ExternalSemaphoreHandleType::OpaqueFd) - .unwrap() - }; + let _fd = unsafe { sem.export_fd(ExternalSemaphoreHandleType::OpaqueFd) }.unwrap(); } }