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 70ee7d5
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions src/distributions/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
use core::num::NonZeroUsize;

use crate::distributions::{Distribution, Uniform};
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")] use alloc::string::String;

/// A distribution to sample items uniformly from a slice.
///
Expand Down Expand Up @@ -69,26 +68,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).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 Expand Up @@ -148,7 +149,11 @@ impl<'a> super::DistString for Slice<'a, char> {

// Split the extension of string to reuse the unused capacities.
// Skip the split for small length or only ascii slice.
let mut extend_len = if max_char_len == 1 || len < 100 { len } else { len / 4 };
let mut extend_len = if max_char_len == 1 || len < 100 {
len
} else {
len / 4
};
let mut remain_len = len;
while extend_len > 0 {
string.reserve(max_char_len * extend_len);
Expand Down

0 comments on commit 70ee7d5

Please sign in to comment.