regd_testing/slice_ext.rs
1// Copyright 2025 Shingo OKAWA. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! This module contains a set of extensions of the existing Rust types.
16
17/// A trait providing extension methods for slices.
18///
19/// This trait adds several useful methods for working with slices. It provides:
20/// - [`choose`]: Randomly selects an element from the slice.
21/// - [`choose_mut`]: Randomly selects and mutably borrows an element from the slice.
22/// - [`shuffle`]: Shuffles the slice in place.
23///
24/// These methods operate on slices of any type `T` and assume that `T` is a type
25/// that can be accessed and modified within the slice.
26///
27/// # Examples
28/// ```
29/// use regd_testing::prelude::*;
30///
31/// let mut numbers = [1, 2, 3, 4, 5];
32/// numbers.shuffle();
33/// println!("Shuffled numbers: {:?}", numbers);
34///
35/// if let Some(choice) = numbers.choose() {
36/// println!("Random choice: {}", choice);
37/// }
38///
39/// if let Some(choice) = numbers.choose_mut() {
40/// *choice = 10;
41/// println!("Modified choice: {}", choice);
42/// }
43/// ```
44///
45/// [`choose`]: Self::choose
46/// [`choose_mut`]: Self::choose_mut
47/// [`shuffle`]: Self::shuffle
48pub trait SliceExt {
49 /// The type of elements in the slice.
50 type Item;
51
52 /// Randomly selects an element from the slice.
53 ///
54 /// # Returns
55 /// - `Some(&Self::Item)` if the slice is non-empty.
56 /// - `None` if the slice is empty.
57 fn choose(&self) -> Option<&Self::Item>;
58
59 /// Randomly selects and mutably borrows an element from the slice.
60 ///
61 /// # Returns
62 /// - `Some(&mut Self::Item)` if the slice is non-empty.
63 /// - `None` if the slice is empty.
64 fn choose_mut(&mut self) -> Option<&mut Self::Item>;
65
66 /// Shuffles the elements of the slice in place.
67 ///
68 /// This method shuffles the slice, reordering its elements randomly.
69 fn shuffle(&mut self);
70}
71
72/// Generates a random index within the specified upper bound.
73///
74/// This function returns a random integer between 0 (inclusive) and `sup` (exclusive),
75/// using a range-based random number generation strategy. It intelligently chooses between
76/// using a `u32` or `usize` bound based on the value of `sup`, ensuring the appropriate
77/// range is selected for generating random numbers.
78///
79/// # Parameters
80/// - `sup`: The upper bound (exclusive) for the generated random index. The function
81/// handles both small and large upper bounds, using a `u32` range for smaller values
82/// and a `usize` range for larger values.
83///
84/// # Returns
85/// - A random `usize` integer in the range `[0, sup)`.
86#[inline]
87fn generate_index(sup: usize) -> usize {
88 if sup <= (u32::MAX as usize) {
89 crate::rand::generate_range(0..sup as u32) as usize
90 } else {
91 crate::rand::generate_range(0..sup)
92 }
93}
94
95impl<T> SliceExt for [T] {
96 type Item = T;
97
98 fn choose(&self) -> Option<&Self::Item> {
99 if self.is_empty() {
100 None
101 } else {
102 Some(&self[generate_index(self.len())])
103 }
104 }
105
106 fn choose_mut(&mut self) -> Option<&mut Self::Item> {
107 if self.is_empty() {
108 None
109 } else {
110 Some(&mut self[generate_index(self.len())])
111 }
112 }
113
114 fn shuffle(&mut self) {
115 for i in (1..self.len()).rev() {
116 self.swap(i, generate_index(i + 1));
117 }
118 }
119}