Skip to content

Commit

Permalink
Replace NonZeroT with NonZero<T> (#2641)
Browse files Browse the repository at this point in the history
* Replace `NonZeroU*` with `NonZero<u*>`

* Re-add the `NonZeroDeviceSize` and `NonNullDeviceAddress` aliases to avoid breakage
  • Loading branch information
Rua authored Feb 7, 2025
1 parent 84f75cc commit ce3b0d6
Show file tree
Hide file tree
Showing 40 changed files with 128 additions and 124 deletions.
8 changes: 4 additions & 4 deletions vulkano-shaders/src/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{bail, codegen::Shader, LinAlgType, MacroInput};
use foldhash::HashMap;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use std::{cmp::Ordering, num::NonZeroUsize};
use std::{cmp::Ordering, num::NonZero};
use syn::{Error, Ident, Result};
use vulkano::shader::spirv::{Decoration, Id, Instruction};

Expand Down Expand Up @@ -589,7 +589,7 @@ impl ComponentCount {
#[derive(Clone, Debug, PartialEq, Eq)]
struct TypeArray {
element_type: Box<Type>,
length: Option<NonZeroUsize>,
length: Option<NonZero<usize>>,
stride: usize,
}

Expand All @@ -608,7 +608,7 @@ impl TypeArray {
assert!(matches!(value.len(), 1 | 2));
let len = value.iter().rev().fold(0u64, |a, &b| (a << 32) | b as u64);

NonZeroUsize::new(len.try_into().unwrap()).ok_or_else(|| {
NonZero::new(len.try_into().unwrap()).ok_or_else(|| {
Error::new_spanned(&shader.source, "arrays must have a non-zero length")
})
}
Expand Down Expand Up @@ -972,7 +972,7 @@ impl ToTokens for Serializer<'_, TypeArray> {

let element_type = Padded(Serializer(element_type, self.1), padding);

if let Some(length) = self.0.length.map(NonZeroUsize::get) {
if let Some(length) = self.0.length.map(NonZero::get) {
tokens.extend(quote! { [#element_type; #length] });
} else {
tokens.extend(quote! { [#element_type] });
Expand Down
12 changes: 6 additions & 6 deletions vulkano-taskgraph/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use smallvec::SmallVec;
use std::{
any::Any,
hash::Hash,
num::{NonZeroU32, NonZeroU64},
num::NonZero,
ops::{BitOr, BitOrAssign},
sync::{
atomic::{AtomicU32, AtomicU64, Ordering},
Expand Down Expand Up @@ -102,7 +102,7 @@ pub(crate) struct SwapchainSemaphoreState {
// FIXME: imported/exported fences
#[derive(Debug)]
pub struct Flight {
frame_count: NonZeroU32,
frame_count: NonZero<u32>,
current_frame: AtomicU64,
fences: SmallVec<[RwLock<Fence>; 3]>,
pub(crate) state: Mutex<FlightState>,
Expand Down Expand Up @@ -246,7 +246,7 @@ impl Resources {
/// - Returns an error when [`Fence::new_unchecked`] returns an error.
pub fn create_flight(&self, frame_count: u32) -> Result<Id<Flight>, VulkanError> {
let frame_count =
NonZeroU32::new(frame_count).expect("a flight with zero frames is not valid");
NonZero::new(frame_count).expect("a flight with zero frames is not valid");

let fences = (0..frame_count.get())
.map(|_| {
Expand Down Expand Up @@ -974,11 +974,11 @@ impl Flight {
#[inline]
#[must_use]
pub fn current_frame_index(&self) -> u32 {
(self.current_frame() % NonZeroU64::from(self.frame_count)) as u32
(self.current_frame() % NonZero::<u64>::from(self.frame_count)) as u32
}

fn previous_frame_index(&self) -> u32 {
(self.current_frame().wrapping_sub(1) % NonZeroU64::from(self.frame_count)) as u32
(self.current_frame().wrapping_sub(1) % NonZero::<u64>::from(self.frame_count)) as u32
}

pub(crate) fn current_fence(&self) -> &RwLock<Fence> {
Expand Down Expand Up @@ -1011,7 +1011,7 @@ impl Flight {
return Ok(());
}

self.fences[(frame % NonZeroU64::from(self.frame_count)) as usize]
self.fences[(frame % NonZero::<u64>::from(self.frame_count)) as usize]
.read()
.wait(timeout)
}
Expand Down
12 changes: 6 additions & 6 deletions vulkano/src/acceleration_structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,19 +90,19 @@ use crate::{
format::{Format, FormatFeatures},
instance::InstanceOwnedDebugWrapper,
macros::{impl_id_counter, vulkan_bitflags, vulkan_enum},
DeviceAddress, DeviceSize, NonNullDeviceAddress, Packed24_8, Requires, RequiresAllOf,
RequiresOneOf, Validated, ValidationError, VulkanError, VulkanObject,
DeviceAddress, DeviceSize, Packed24_8, Requires, RequiresAllOf, RequiresOneOf, Validated,
ValidationError, VulkanError, VulkanObject,
};
use ash::vk;
use bytemuck::{Pod, Zeroable};
use std::{fmt::Debug, hash::Hash, mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc};
use std::{fmt::Debug, hash::Hash, mem::MaybeUninit, num::NonZero, ptr, sync::Arc};

/// An opaque data structure that is used to accelerate spatial queries on geometry data.
#[derive(Debug)]
pub struct AccelerationStructure {
device: InstanceOwnedDebugWrapper<Arc<Device>>,
handle: vk::AccelerationStructureKHR,
id: NonZeroU64,
id: NonZero<u64>,

create_flags: AccelerationStructureCreateFlags,
buffer: Subbuffer<[u8]>,
Expand Down Expand Up @@ -245,7 +245,7 @@ impl AccelerationStructure {
///
/// The device address of the acceleration structure may be different from the device address
/// of the underlying buffer.
pub fn device_address(&self) -> NonNullDeviceAddress {
pub fn device_address(&self) -> NonZero<DeviceAddress> {
let info_vk = vk::AccelerationStructureDeviceAddressInfoKHR::default()
.acceleration_structure(self.handle);
let fns = self.device.fns();
Expand All @@ -256,7 +256,7 @@ impl AccelerationStructure {
)
};

NonNullDeviceAddress::new(ptr).unwrap()
NonZero::new(ptr).unwrap()
}
}

Expand Down
11 changes: 6 additions & 5 deletions vulkano/src/buffer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ use crate::{
},
range_map::RangeMap,
sync::{future::AccessError, AccessConflict, CurrentAccess, Sharing},
DeviceSize, NonNullDeviceAddress, Requires, RequiresAllOf, RequiresOneOf, Validated,
ValidationError, Version, VulkanError, VulkanObject,
DeviceAddress, DeviceSize, Requires, RequiresAllOf, RequiresOneOf, Validated, ValidationError,
Version, VulkanError, VulkanObject,
};
use ash::vk;
use parking_lot::{Mutex, MutexGuard};
Expand All @@ -94,6 +94,7 @@ use std::{
fmt::{Display, Formatter},
hash::{Hash, Hasher},
marker::PhantomData,
num::NonZero,
ops::Range,
sync::Arc,
};
Expand Down Expand Up @@ -470,7 +471,7 @@ impl Buffer {

/// Returns the device address for this buffer.
// TODO: Caching?
pub fn device_address(&self) -> Result<NonNullDeviceAddress, Box<ValidationError>> {
pub fn device_address(&self) -> Result<NonZero<DeviceAddress>, Box<ValidationError>> {
self.validate_device_address()?;

Ok(unsafe { self.device_address_unchecked() })
Expand Down Expand Up @@ -502,7 +503,7 @@ impl Buffer {
}

#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
pub unsafe fn device_address_unchecked(&self) -> NonNullDeviceAddress {
pub unsafe fn device_address_unchecked(&self) -> NonZero<DeviceAddress> {
let device = self.device();

let info_vk = vk::BufferDeviceAddressInfo::default().buffer(self.handle());
Expand All @@ -519,7 +520,7 @@ impl Buffer {
unsafe { func(device.handle(), &info_vk) }
};

NonNullDeviceAddress::new(ptr).unwrap()
NonZero::new(ptr).unwrap()
}

pub(crate) fn state(&self) -> MutexGuard<'_, BufferState> {
Expand Down
14 changes: 7 additions & 7 deletions vulkano/src/buffer/subbuffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
is_aligned, DeviceAlignment, MappedMemoryRange,
},
sync::HostAccessError,
DeviceSize, NonNullDeviceAddress, NonZeroDeviceSize, ValidationError,
DeviceAddress, DeviceSize, ValidationError,
};
use ash::vk;
use bytemuck::AnyBitPattern;
Expand All @@ -20,6 +20,7 @@ use std::{
hash::{Hash, Hasher},
marker::PhantomData,
mem::{self, align_of, size_of},
num::NonZero,
ops::{Deref, DerefMut, Range, RangeBounds},
ptr::{self, NonNull},
sync::Arc,
Expand Down Expand Up @@ -129,23 +130,23 @@ impl<T: ?Sized> Subbuffer<T> {
}

/// Returns the device address for this subbuffer.
pub fn device_address(&self) -> Result<NonNullDeviceAddress, Box<ValidationError>> {
pub fn device_address(&self) -> Result<NonZero<DeviceAddress>, Box<ValidationError>> {
self.buffer().device_address().map(|ptr| {
// SAFETY: The original address came from the Vulkan implementation, and allocation
// sizes are guaranteed to not exceed `DeviceLayout::MAX_SIZE`, so the offset better be
// in range.
unsafe { NonNullDeviceAddress::new_unchecked(ptr.get() + self.offset) }
unsafe { NonZero::new_unchecked(ptr.get() + self.offset) }
})
}

#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
pub unsafe fn device_address_unchecked(&self) -> NonNullDeviceAddress {
pub unsafe fn device_address_unchecked(&self) -> NonZero<DeviceAddress> {
let buffer_device_address = unsafe { self.buffer().device_address_unchecked() };

// SAFETY: The original address came from the Vulkan implementation, and allocation
// sizes are guaranteed to not exceed `DeviceLayout::MAX_SIZE`, so the offset better be
// in range.
unsafe { NonNullDeviceAddress::new_unchecked(buffer_device_address.get() + self.offset) }
unsafe { NonZero::new_unchecked(buffer_device_address.get() + self.offset) }
}

/// Casts the subbuffer to a slice of raw bytes.
Expand Down Expand Up @@ -1095,8 +1096,7 @@ impl BufferContentsLayout {
// SAFETY: `BufferContentsLayout`'s invariant guarantees that the alignment of the
// element type doesn't exceed 64, which together with the overflow invariant of
// `DeviceLayout` means that this can't overflow.
let padded_head_size =
unsafe { NonZeroDeviceSize::new_unchecked(padded_head_size) };
let padded_head_size = unsafe { NonZero::new_unchecked(padded_head_size) };

// We have to align the head to the alignment of the element type, so that the
// struct as a whole is aligned correctly when a different struct is extended with
Expand Down
4 changes: 2 additions & 2 deletions vulkano/src/buffer/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::{
};
use ash::vk;
use smallvec::SmallVec;
use std::{marker::PhantomData, mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc};
use std::{marker::PhantomData, mem::MaybeUninit, num::NonZero, ptr, sync::Arc};

/// A raw buffer, with no memory backing it.
///
Expand All @@ -31,7 +31,7 @@ use std::{marker::PhantomData, mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc
pub struct RawBuffer {
handle: vk::Buffer,
device: InstanceOwnedDebugWrapper<Arc<Device>>,
id: NonZeroU64,
id: NonZero<u64>,

flags: BufferCreateFlags,
size: DeviceSize,
Expand Down
4 changes: 2 additions & 2 deletions vulkano/src/buffer/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ use crate::{
DeviceSize, Validated, ValidationError, Version, VulkanError, VulkanObject,
};
use ash::vk;
use std::{mem::MaybeUninit, num::NonZeroU64, ops::Range, ptr, sync::Arc};
use std::{mem::MaybeUninit, num::NonZero, ops::Range, ptr, sync::Arc};

/// Represents a way for the GPU to interpret buffer data. See the documentation of the
/// `view` module.
#[derive(Debug)]
pub struct BufferView {
handle: vk::BufferView,
subbuffer: Subbuffer<[u8]>,
id: NonZeroU64,
id: NonZero<u64>,

format: Format,
format_features: FormatFeatures,
Expand Down
6 changes: 3 additions & 3 deletions vulkano/src/command_buffer/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{
};
use ash::vk;
use smallvec::SmallVec;
use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc};
use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, num::NonZero, ptr, sync::Arc};

/// Represents a Vulkan command pool.
///
Expand All @@ -29,7 +29,7 @@ use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, num::NonZeroU64, pt
pub struct CommandPool {
handle: vk::CommandPool,
device: InstanceOwnedDebugWrapper<Arc<Device>>,
id: NonZeroU64,
id: NonZero<u64>,

flags: CommandPoolCreateFlags,
queue_family_index: u32,
Expand Down Expand Up @@ -485,7 +485,7 @@ impl Default for CommandBufferAllocateInfo {
pub struct CommandPoolAlloc {
handle: vk::CommandBuffer,
device: InstanceOwnedDebugWrapper<Arc<Device>>,
id: NonZeroU64,
id: NonZero<u64>,
level: CommandBufferLevel,
}

Expand Down
4 changes: 2 additions & 2 deletions vulkano/src/descriptor_set/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::{
cell::UnsafeCell,
fmt::{Debug, Error as FmtError, Formatter},
mem,
num::NonZeroU64,
num::NonZero,
ptr,
sync::Arc,
};
Expand Down Expand Up @@ -175,7 +175,7 @@ impl AllocationHandle {
#[derive(Debug)]
pub struct StandardDescriptorSetAllocator {
device: InstanceOwnedDebugWrapper<Arc<Device>>,
pools: ThreadLocal<UnsafeCell<SortedMap<NonZeroU64, Entry>>>,
pools: ThreadLocal<UnsafeCell<SortedMap<NonZero<u64>, Entry>>>,
create_info: StandardDescriptorSetAllocatorCreateInfo,
}

Expand Down
4 changes: 2 additions & 2 deletions vulkano/src/descriptor_set/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ use crate::{
use ash::vk;
use foldhash::HashMap;
use smallvec::SmallVec;
use std::{collections::BTreeMap, mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc};
use std::{collections::BTreeMap, mem::MaybeUninit, num::NonZero, ptr, sync::Arc};

/// Describes to the Vulkan implementation the layout of all descriptors within a descriptor set.
#[derive(Debug)]
pub struct DescriptorSetLayout {
handle: vk::DescriptorSetLayout,
device: InstanceOwnedDebugWrapper<Arc<Device>>,
id: NonZeroU64,
id: NonZero<u64>,

flags: DescriptorSetLayoutCreateFlags,
bindings: BTreeMap<u32, DescriptorSetLayoutBinding>,
Expand Down
6 changes: 3 additions & 3 deletions vulkano/src/descriptor_set/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
use ash::vk;
use foldhash::HashMap;
use smallvec::SmallVec;
use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc};
use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, num::NonZero, ptr, sync::Arc};

/// Pool that descriptors are allocated from.
///
Expand All @@ -22,7 +22,7 @@ use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, num::NonZeroU64, pt
pub struct DescriptorPool {
handle: vk::DescriptorPool,
device: InstanceOwnedDebugWrapper<Arc<Device>>,
id: NonZeroU64,
id: NonZero<u64>,

flags: DescriptorPoolCreateFlags,
max_sets: u32,
Expand Down Expand Up @@ -697,7 +697,7 @@ impl DescriptorSetAllocateInfo {
#[derive(Debug)]
pub struct DescriptorPoolAlloc {
handle: vk::DescriptorSet,
id: NonZeroU64,
id: NonZero<u64>,
layout: DeviceOwnedDebugWrapper<Arc<DescriptorSetLayout>>,
variable_descriptor_count: u32,
}
Expand Down
4 changes: 2 additions & 2 deletions vulkano/src/device/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ use std::{
fs::File,
marker::PhantomData,
mem::MaybeUninit,
num::NonZeroU64,
num::NonZero,
ops::Deref,
ptr, slice,
sync::{
Expand All @@ -149,7 +149,7 @@ pub struct Device {
handle: vk::Device,
// NOTE: `physical_devices` always contains this.
physical_device: InstanceOwnedDebugWrapper<Arc<PhysicalDevice>>,
id: NonZeroU64,
id: NonZero<u64>,

enabled_extensions: DeviceExtensions,
enabled_features: DeviceFeatures,
Expand Down
4 changes: 2 additions & 2 deletions vulkano/src/device/physical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use std::{
fmt::{Debug, Error as FmtError, Formatter},
marker::PhantomData,
mem::MaybeUninit,
num::NonZeroU64,
num::NonZero,
ptr,
sync::Arc,
};
Expand Down Expand Up @@ -62,7 +62,7 @@ use std::{
pub struct PhysicalDevice {
handle: vk::PhysicalDevice,
instance: DebugWrapper<Arc<Instance>>,
id: NonZeroU64,
id: NonZero<u64>,

// Data queried at `PhysicalDevice` creation.
api_version: Version,
Expand Down
Loading

0 comments on commit ce3b0d6

Please sign in to comment.