Skip to content

Commit

Permalink
Use choices struct field at creation time instead of using unsafe at …
Browse files Browse the repository at this point in the history
…call time

Signed-off-by: Justus Fluegel <justusfluegel@gmail.com>
  • Loading branch information
JustusFluegel committed Mar 5, 2024
1 parent 5df12b1 commit 1f08009
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/distributions/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,26 +69,28 @@ use alloc::string::String;
pub struct Slice<'a, T> {
slice: &'a [T],
range: Uniform<usize>,
choices: NonZeroUsize,
}

impl<'a, T> Slice<'a, T> {
/// Create a new `Slice` instance which samples uniformly from the slice.
/// Returns `Err` if the slice is empty.
pub fn new(slice: &'a [T]) -> Result<Self, EmptySlice> {
match slice.len() {
0 => Err(EmptySlice),
len => Ok(Self {
slice,
range: Uniform::new(0, len).unwrap(),
}),
}
let len = match NonZeroUsize::new(slice.len()) {
None => return Err(EmptySlice),
Some(len) => len,
};

Ok(Self {
slice,
range: Uniform::new(0, len.get()).unwrap(),
choices: len,
})
}

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

Expand Down

0 comments on commit 1f08009

Please sign in to comment.