Skip to content

Commit 1f08009

Browse files
committed
Use choices struct field at creation time instead of using unsafe at call time
Signed-off-by: Justus Fluegel <[email protected]>
1 parent 5df12b1 commit 1f08009

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/distributions/slice.rs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -69,26 +69,28 @@ use alloc::string::String;
6969
pub struct Slice<'a, T> {
7070
slice: &'a [T],
7171
range: Uniform<usize>,
72+
choices: NonZeroUsize,
7273
}
7374

7475
impl<'a, T> Slice<'a, T> {
7576
/// Create a new `Slice` instance which samples uniformly from the slice.
7677
/// Returns `Err` if the slice is empty.
7778
pub fn new(slice: &'a [T]) -> Result<Self, EmptySlice> {
78-
match slice.len() {
79-
0 => Err(EmptySlice),
80-
len => Ok(Self {
81-
slice,
82-
range: Uniform::new(0, len).unwrap(),
83-
}),
84-
}
79+
let len = match NonZeroUsize::new(slice.len()) {
80+
None => return Err(EmptySlice),
81+
Some(len) => len,
82+
};
83+
84+
Ok(Self {
85+
slice,
86+
range: Uniform::new(0, len.get()).unwrap(),
87+
choices: len,
88+
})
8589
}
8690

8791
/// Returns the count of choices in this distribution
8892
pub fn num_choices(&self) -> NonZeroUsize {
89-
// Safety: at construction time, it was ensured that the slice was
90-
// non-empty, as such the length can never be 0.
91-
unsafe { NonZeroUsize::new_unchecked(self.slice.len()) }
93+
self.choices
9294
}
9395
}
9496

0 commit comments

Comments
 (0)