Skip to content

Commit 7f532f5

Browse files
committed
ByteAddressableBuffer: unify bounds check in separate method
1 parent fcfe77d commit 7f532f5

File tree

1 file changed

+20
-23
lines changed

1 file changed

+20
-23
lines changed

crates/spirv-std/src/byte_addressable_buffer.rs

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,23 @@ pub struct ByteAddressableBuffer<T> {
6767
pub data: T,
6868
}
6969

70+
fn bounds_check<T>(data: &[u32], byte_index: u32) {
71+
let sizeof = mem::size_of::<T>() as u32;
72+
if byte_index % 4 != 0 {
73+
panic!("`byte_index` should be a multiple of 4");
74+
}
75+
if byte_index + sizeof > data.len() as u32 {
76+
let last_byte = byte_index + sizeof;
77+
panic!(
78+
"index out of bounds: the len is {} but loading {} bytes at `byte_index` {} reads until {} (exclusive)",
79+
data.len(),
80+
sizeof,
81+
byte_index,
82+
last_byte,
83+
);
84+
}
85+
}
86+
7087
impl<'a> ByteAddressableBuffer<&'a [u32]> {
7188
/// Creates a `ByteAddressableBuffer` from the untyped blob of data.
7289
#[inline]
@@ -80,16 +97,7 @@ impl<'a> ByteAddressableBuffer<&'a [u32]> {
8097
/// # Safety
8198
/// See [`Self`].
8299
pub unsafe fn load<T>(&self, byte_index: u32) -> T {
83-
if byte_index % 4 != 0 {
84-
panic!("`byte_index` should be a multiple of 4");
85-
}
86-
if byte_index + mem::size_of::<T>() as u32 > self.data.len() as u32 {
87-
panic!(
88-
"index out of bounds: the len is {} but the `byte_index` is {}",
89-
self.data.len(),
90-
byte_index
91-
);
92-
}
100+
bounds_check::<T>(self.data, byte_index);
93101
buffer_load_intrinsic(self.data, byte_index)
94102
}
95103

@@ -116,16 +124,7 @@ impl<'a> ByteAddressableBuffer<&'a mut [u32]> {
116124
/// # Safety
117125
/// See [`Self`].
118126
pub unsafe fn load<T>(&self, byte_index: u32) -> T {
119-
if byte_index % 4 != 0 {
120-
panic!("`byte_index` should be a multiple of 4");
121-
}
122-
if byte_index + mem::size_of::<T>() as u32 > self.data.len() as u32 {
123-
panic!(
124-
"index out of bounds: the len is {} but the `byte_index` is {}",
125-
self.data.len(),
126-
byte_index
127-
);
128-
}
127+
bounds_check::<T>(self.data, byte_index);
129128
buffer_load_intrinsic(self.data, byte_index)
130129
}
131130

@@ -144,9 +143,7 @@ impl<'a> ByteAddressableBuffer<&'a mut [u32]> {
144143
/// # Safety
145144
/// See [`Self`].
146145
pub unsafe fn store<T>(&mut self, byte_index: u32, value: T) {
147-
if byte_index + mem::size_of::<T>() as u32 > self.data.len() as u32 {
148-
panic!("Index out of range");
149-
}
146+
bounds_check::<T>(self.data, byte_index);
150147
buffer_store_intrinsic(self.data, byte_index, value);
151148
}
152149

0 commit comments

Comments
 (0)