Skip to content

Commit 70ee7d5

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 70ee7d5

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

src/distributions/slice.rs

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99
use core::num::NonZeroUsize;
1010

1111
use crate::distributions::{Distribution, Uniform};
12-
#[cfg(feature = "alloc")]
13-
use alloc::string::String;
12+
#[cfg(feature = "alloc")] use alloc::string::String;
1413

1514
/// A distribution to sample items uniformly from a slice.
1615
///
@@ -69,26 +68,28 @@ use alloc::string::String;
6968
pub struct Slice<'a, T> {
7069
slice: &'a [T],
7170
range: Uniform<usize>,
71+
choices: NonZeroUsize,
7272
}
7373

7474
impl<'a, T> Slice<'a, T> {
7575
/// Create a new `Slice` instance which samples uniformly from the slice.
7676
/// Returns `Err` if the slice is empty.
7777
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-
}
78+
let len = match NonZeroUsize::new(slice.len()) {
79+
None => return Err(EmptySlice),
80+
Some(len) => len,
81+
};
82+
83+
Ok(Self {
84+
slice,
85+
range: Uniform::new(0, len).unwrap(),
86+
choices: len,
87+
})
8588
}
8689

8790
/// Returns the count of choices in this distribution
8891
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()) }
92+
self.choices
9293
}
9394
}
9495

@@ -148,7 +149,11 @@ impl<'a> super::DistString for Slice<'a, char> {
148149

149150
// Split the extension of string to reuse the unused capacities.
150151
// Skip the split for small length or only ascii slice.
151-
let mut extend_len = if max_char_len == 1 || len < 100 { len } else { len / 4 };
152+
let mut extend_len = if max_char_len == 1 || len < 100 {
153+
len
154+
} else {
155+
len / 4
156+
};
152157
let mut remain_len = len;
153158
while extend_len > 0 {
154159
string.reserve(max_char_len * extend_len);

0 commit comments

Comments
 (0)