rand_bits/
lib.rs

1//! Utility functions for generating random numbers with a fixed number of set bits (ones).
2//!
3//! # Example
4//!
5//! ```rust
6//! use rand::thread_rng;
7//! use rand_bits::RngBits;
8//!
9//! let mut rng = thread_rng();
10//! let x: u8 = rng.gen_bits(4); // generates a u8 with 4 set bits
11//! assert_eq!(x.count_ones(), 4);
12//! let y: u16 = rng.gen_bits(15); // generates a u16 with 15 set bits
13//! assert_eq!(y.count_ones(), 15);
14//! let z: u64 = rng.gen_bits(1); // generates a u64 with 1 set bits
15//! assert_eq!(z.count_ones(), 1);
16//! ```
17//!
18//! # License
19//!
20//! This crate is licensed under the MIT License.
21
22#![forbid(unsafe_code)]
23
24use std::cmp::min;
25
26use phf::{phf_map, Map};
27use rand::Rng;
28
29const MAPPING: Map<u32, &'static [u8]> = phf_map! {
30    1u32 => &[0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80],
31    2u32 => &[0x03, 0x05, 0x06, 0x09, 0x0A, 0x0C, 0x11, 0x12, 0x14, 0x18, 0x21, 0x22, 0x24, 0x28, 0x30, 0x41, 0x42, 0x44, 0x48, 0x50, 0x60, 0x81, 0x82, 0x84, 0x88, 0x90, 0xA0, 0xC0],
32    3u32 => &[0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x15, 0x16, 0x19, 0x1A, 0x1C, 0x23, 0x25, 0x26, 0x29, 0x2A, 0x2C, 0x31, 0x32, 0x34, 0x38, 0x43, 0x45, 0x46, 0x49, 0x4A, 0x4C, 0x51, 0x52, 0x54, 0x58, 0x61, 0x62, 0x64, 0x68, 0x70, 0x83, 0x85, 0x86, 0x89, 0x8A, 0x8C, 0x91, 0x92, 0x94, 0x98, 0xA1, 0xA2, 0xA4, 0xA8, 0xB0, 0xC1, 0xC2, 0xC4, 0xC8, 0xD0, 0xE0],
33    4u32 => &[0x0F, 0x17, 0x1B, 0x1D, 0x1E, 0x27, 0x2B, 0x2D, 0x2E, 0x33, 0x35, 0x36, 0x39, 0x3A, 0x3C, 0x47, 0x4B, 0x4D, 0x4E, 0x53, 0x55, 0x56, 0x59, 0x5A, 0x5C, 0x63, 0x65, 0x66, 0x69, 0x6A, 0x6C, 0x71, 0x72, 0x74, 0x78, 0x87, 0x8B, 0x8D, 0x8E, 0x93, 0x95, 0x96, 0x99, 0x9A, 0x9C, 0xA3, 0xA5, 0xA6, 0xA9, 0xAA, 0xAC, 0xB1, 0xB2, 0xB4, 0xB8, 0xC3, 0xC5, 0xC6, 0xC9, 0xCA, 0xCC, 0xD1, 0xD2, 0xD4, 0xD8, 0xE1, 0xE2, 0xE4, 0xE8, 0xF0],
34};
35
36/// A generic random value distribution, implemented for many primitive types.
37/// Usually generates values with a numerically uniform distribution, and with a
38/// range appropriate to the type.
39///
40/// Based on [`rand::distributions::Standard`].
41pub struct Standard;
42
43/// Types (distributions) that can be used to create a random instance of `T`.
44///
45/// Based on [`rand::distributions::Distribution`].
46pub trait Distribution<T> {
47    /// Generate a random value of `T`, using `rng` as the source of randomness.
48    fn sample<R>(&self, rng: &mut R, bits: u32) -> T
49    where
50        R: Rng + ?Sized;
51}
52
53impl Distribution<u8> for Standard {
54    fn sample<R>(&self, rng: &mut R, bits: u32) -> u8
55    where
56        R: Rng + ?Sized,
57    {
58        match bits {
59            0 => u8::MIN,
60            u8::BITS => u8::MAX,
61            1..=4 => {
62                let values = MAPPING.get(&bits).expect("bits count out of range");
63                let index = rng.gen_range(0..values.len());
64                values[index]
65            },
66            5..=7 => {
67                let bits = u8::BITS - bits;
68                Distribution::<u8>::sample(self, rng, bits) ^ 0xFF
69            },
70            _ => panic!("bits count out of range"),
71        }
72    }
73}
74
75impl Distribution<u16> for Standard {
76    fn sample<R>(&self, rng: &mut R, bits: u32) -> u16
77    where
78        R: Rng + ?Sized,
79    {
80        match bits {
81            0 => u16::MIN,
82            u16::BITS => u16::MAX,
83            bits if (1..u16::BITS).contains(&bits) => {
84                let min_high_bits = bits.checked_sub(u8::BITS).unwrap_or_default();
85                let max_high_bits = min(bits, u8::BITS);
86                let high_bits = rng.gen_range(min_high_bits..=max_high_bits);
87                let low_bits = bits - high_bits;
88
89                let mut value = Distribution::<u8>::sample(self, rng, high_bits) as u16;
90                value <<= u8::BITS;
91                value |= Distribution::<u8>::sample(self, rng, low_bits) as u16;
92                value
93            },
94            _ => panic!("bits count out of range"),
95        }
96    }
97}
98
99impl Distribution<u32> for Standard {
100    fn sample<R>(&self, rng: &mut R, bits: u32) -> u32
101    where
102        R: Rng + ?Sized,
103    {
104        match bits {
105            0 => u32::MIN,
106            u32::BITS => u32::MAX,
107            bits if (1..u32::BITS).contains(&bits) => {
108                let min_high_bits = bits.checked_sub(u16::BITS).unwrap_or_default();
109                let max_high_bits = min(bits, u16::BITS);
110                let high_bits = rng.gen_range(min_high_bits..=max_high_bits);
111                let low_bits = bits - high_bits;
112
113                let mut value = Distribution::<u16>::sample(self, rng, high_bits) as u32;
114                value <<= u16::BITS;
115                value |= Distribution::<u16>::sample(self, rng, low_bits) as u32;
116                value
117            },
118            _ => panic!("bits count out of range"),
119        }
120    }
121}
122
123impl Distribution<u64> for Standard {
124    fn sample<R>(&self, rng: &mut R, bits: u32) -> u64
125    where
126        R: Rng + ?Sized,
127    {
128        match bits {
129            0 => u64::MIN,
130            u64::BITS => u64::MAX,
131            bits if (1..u64::BITS).contains(&bits) => {
132                let min_high_bits = bits.checked_sub(u32::BITS).unwrap_or_default();
133                let max_high_bits = min(bits, u32::BITS);
134                let high_bits = rng.gen_range(min_high_bits..=max_high_bits);
135                let low_bits = bits - high_bits;
136
137                let mut value = Distribution::<u32>::sample(self, rng, high_bits) as u64;
138                value <<= u32::BITS;
139                value |= Distribution::<u32>::sample(self, rng, low_bits) as u64;
140                value
141            },
142            _ => panic!("bits count out of range"),
143        }
144    }
145}
146
147impl Distribution<u128> for Standard {
148    fn sample<R>(&self, rng: &mut R, bits: u32) -> u128
149    where
150        R: Rng + ?Sized,
151    {
152        match bits {
153            0 => u128::MIN,
154            u128::BITS => u128::MAX,
155            bits if (1..u128::BITS).contains(&bits) => {
156                let min_high_bits = bits.checked_sub(u64::BITS).unwrap_or_default();
157                let max_high_bits = min(bits, u64::BITS);
158                let high_bits = rng.gen_range(min_high_bits..=max_high_bits);
159                let low_bits = bits - high_bits;
160
161                let mut value = Distribution::<u64>::sample(self, rng, high_bits) as u128;
162                value <<= u64::BITS;
163                value |= Distribution::<u64>::sample(self, rng, low_bits) as u128;
164                value
165            },
166            _ => panic!("bits count out of range"),
167        }
168    }
169}
170
171/// An automatically-implemented extension trait on [`rand::Rng`].
172///
173/// # Example:
174///
175/// ```rust
176/// # use rand::thread_rng;
177/// use rand_bits::RngBits;
178///
179/// fn foo<R>(rng: &mut R) -> u16
180/// where
181///     R: RngBits + ?Sized,
182/// {
183///     rng.gen_bits(16)
184/// }
185///
186/// # let v = foo(&mut thread_rng());
187/// ```
188pub trait RngBits: Rng {
189    /// Return a random value supporting the [`Standard`] distribution with a chosen
190    /// number of bits set to active.
191    ///
192    /// # Example
193    ///
194    /// ```rust
195    /// use rand::thread_rng;
196    /// use rand_bits::RngBits;
197    ///
198    /// let mut rng = thread_rng();
199    /// let x: u32 = rng.gen_bits(11);
200    /// println!("{}", x);
201    /// ```
202    fn gen_bits<T>(&mut self, bits: u32) -> T
203    where
204        Standard: Distribution<T>,
205    {
206        Standard.sample(self, bits)
207    }
208}
209
210impl<R> RngBits for R where R: Rng {}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn u8() {
218        let mut rng = rand::thread_rng();
219        for i in 0..=u8::BITS {
220            let n: u8 = rng.gen_bits(i);
221            assert_eq!(n.count_ones(), i);
222        }
223    }
224
225    #[test]
226    fn u16() {
227        let mut rng = rand::thread_rng();
228        for i in 0..=u16::BITS {
229            let n: u16 = rng.gen_bits(i);
230            assert_eq!(n.count_ones(), i);
231        }
232    }
233
234    #[test]
235    fn u32() {
236        let mut rng = rand::thread_rng();
237        for i in 0..=u32::BITS {
238            let n: u32 = rng.gen_bits(i);
239            assert_eq!(n.count_ones(), i);
240        }
241    }
242
243    #[test]
244    fn u64() {
245        let mut rng = rand::thread_rng();
246        for i in 0..=u64::BITS {
247            let n: u64 = rng.gen_bits(i);
248            assert_eq!(n.count_ones(), i);
249        }
250    }
251
252    #[test]
253    fn u128() {
254        let mut rng = rand::thread_rng();
255        for i in 0..=u128::BITS {
256            let n: u128 = rng.gen_bits(i);
257            assert_eq!(n.count_ones(), i);
258        }
259    }
260}