Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add .choices() method to the Slice distribution #1402

Merged
merged 6 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ A [separate changelog is kept for rand_core](rand_core/CHANGELOG.md).

You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.html) useful.

## [0.9.1] - unreleased
- Add the `Slice::num_choices` method to the Slice distribution (#1402)

## [0.9.0-alpha.0] - 2024-02-18
This is a pre-release. To depend on this version, use `rand = "=0.9.0-alpha.0"` to prevent automatic updates (which can be expected to include breaking changes).

Expand Down
22 changes: 15 additions & 7 deletions src/distributions/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::num::NonZeroUsize;

use crate::distributions::{Distribution, Uniform};
#[cfg(feature = "alloc")]
use alloc::string::String;
Expand Down Expand Up @@ -67,19 +69,25 @@ use alloc::string::String;
pub struct Slice<'a, T> {
slice: &'a [T],
range: Uniform<usize>,
num_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 num_choices = NonZeroUsize::new(slice.len()).ok_or(EmptySlice)?;

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

/// Returns the count of choices in this distribution
pub fn num_choices(&self) -> NonZeroUsize {
self.num_choices
}
}

Expand Down
Loading