File tree Expand file tree Collapse file tree 1 file changed +12
-10
lines changed Expand file tree Collapse file tree 1 file changed +12
-10
lines changed Original file line number Diff line number Diff line change @@ -69,26 +69,28 @@ use alloc::string::String;
6969pub struct Slice < ' a , T > {
7070 slice : & ' a [ T ] ,
7171 range : Uniform < usize > ,
72+ choices : NonZeroUsize ,
7273}
7374
7475impl < ' 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
You can’t perform that action at this time.
0 commit comments