Skip to content

Commit e523faa

Browse files
authored
Merge pull request #123 from dtolnay/div
Perform size division using NonZeroUsize
2 parents 30020d3 + d8c95d3 commit e523faa

1 file changed

Lines changed: 7 additions & 8 deletions

File tree

src/distributed_slice.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use core::fmt::{self, Debug};
2+
#[cfg(any(target_os = "uefi", target_os = "windows"))]
23
use core::hint;
34
use core::mem;
5+
use core::num::NonZeroUsize;
46
use core::ops::Deref;
57
use core::slice;
68

@@ -131,6 +133,7 @@ use crate::__private::Slice;
131133
/// ```
132134
pub struct DistributedSlice<T: ?Sized + Slice> {
133135
name: &'static str,
136+
stride: NonZeroUsize,
134137
section_start: StaticPtr<T::Element>,
135138
section_stop: StaticPtr<T::Element>,
136139
dupcheck_start: StaticPtr<isize>,
@@ -163,12 +166,13 @@ impl<T> DistributedSlice<[T]> {
163166
dupcheck_start: *const (),
164167
dupcheck_stop: *const (),
165168
) -> Self {
166-
if mem::size_of::<T>() == 0 {
169+
let Some(stride) = NonZeroUsize::new(mem::size_of::<T>()) else {
167170
panic!("#[distributed_slice] requires that the slice element type has nonzero size");
168-
}
171+
};
169172

170173
DistributedSlice {
171174
name,
175+
stride,
172176
section_start: StaticPtr {
173177
ptr: section_start.cast::<T>(),
174178
},
@@ -230,15 +234,10 @@ impl<T> DistributedSlice<[T]> {
230234
panic!("duplicate #[distributed_slice] with name \"{}\"", self.name);
231235
}
232236

233-
let stride = mem::size_of::<T>();
234237
let start = self.section_start.ptr;
235238
let stop = self.section_stop.ptr;
236239
let byte_offset = stop as usize - start as usize;
237-
let Some(len) = byte_offset.checked_div(stride) else {
238-
// The #[distributed_slice] call checks `size_of::<T>() > 0` before
239-
// using the unsafe `private_new`.
240-
unsafe { hint::unreachable_unchecked() }
241-
};
240+
let len = byte_offset / self.stride;
242241

243242
// On Windows, the implementation involves growing a &[T; 0] to
244243
// encompass elements that we have asked the linker to place immediately

0 commit comments

Comments
 (0)