macro_toolset/string/rand.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
//! Random string.
use rand::{distributions::Slice, Rng};
use super::{NumStr, StringExtT};
use crate::random::fast_random;
#[derive(Debug, Clone, Copy, Default)]
/// Randon hex-like string, with fix length.
///
/// For better performance, the underlying random number is generated by
/// xorshift algorithm then converted to hex string with [`NumStr`].
///
/// By default, the length is 16.
///
/// # Generic Parameters
///
/// - `L`: The length of the string. Max 16 (u64).
/// - `RP`: Repeat `L` for `RP` times.
/// - `LP`: Lefted length. Max 16.
///
/// For example, if you need a string with length 56, you may specify `L` as 16,
/// `RP` as 56 / 16 = 3, and `LP` as 56 % 16 = 8.
///
/// Since `#![feature(generic_const_exprs)]` is not stable, we have to make use
/// of these complex const generics.
///
/// Notice: will check if params are valid when you push this into the
/// [`StringExt`](super::StringExt), or panic in debug mode, work normally but
/// slower in release mode.
pub struct RandHexStr<const L: usize = 16, const RP: usize = 1, const LP: usize = 0>;
impl<const L: usize, const RP: usize, const LP: usize> StringExtT for RandHexStr<L, RP, LP> {
fn push_to_string(self, string: &mut Vec<u8>) {
match L {
1..=16 => {
for _ in 0..RP {
NumStr::hex_default(fast_random())
.set_resize_len::<L>()
.push_to_string(string);
}
if LP > 0 {
debug_assert!(LP <= 16, "LP should be 0..=16");
NumStr::hex_default(fast_random())
.set_resize_len::<LP>()
.push_to_string(string);
}
}
0 => {}
_ => {
#[cfg(any(debug_assertions, test))]
unreachable!("L should be 0..=16");
#[cfg(not(any(debug_assertions, test)))]
// For RELEASE mode, avoid panic but still generate random string like general
// RandStr does.
string.extend(
rand::thread_rng()
.sample_iter(&Slice::new(b"0123456789abcdef").unwrap())
.take(L * RP + LP),
);
}
}
}
}
impl RandHexStr {
#[inline]
/// Create a new [`RandHexStr`] and generate simple random hex-like string
/// with length 16 (default).
///
/// # Example
///
/// ```rust
/// # use macro_toolset::string::{RandHexStr, StringExtT};
/// let rand_str = RandHexStr::new_default().to_string_ext();
/// assert_eq!(rand_str.len(), 16);
/// ```
pub const fn new_default() -> Self {
Self
}
}
impl<const L: usize, const RP: usize, const LP: usize> RandHexStr<L, RP, LP> {
#[inline]
/// Create a new [`RandStr`] and generate random hex-like string with
/// length setting by `L`, `RP`, `LP`.
///
/// # Example
///
/// ```rust
/// # use macro_toolset::string::{RandHexStr, StringExtT};
/// let rand_str = RandHexStr::<16, 3, 8>::new().to_string_ext();
/// assert_eq!(rand_str.len(), 56);
/// ```
pub const fn new() -> Self {
RandHexStr
}
#[inline]
/// Set `L`.
///
/// You may prefer [`RandHexStr::<L, RP, LP>::new`](Self::new).
pub const fn with_l<const NL: usize>(self) -> RandHexStr<NL, RP, LP> {
RandHexStr
}
#[inline]
/// Set `RP`.
///
/// You may prefer [`RandHexStr::<L, RP, LP>::new`](Self::new).
pub const fn with_rp<const NRP: usize>(self) -> RandHexStr<L, NRP, LP> {
RandHexStr
}
#[inline]
/// Set `LP`.
///
/// You may prefer [`RandHexStr::<L, RP, LP>::new`](Self::new).
pub const fn with_lp<const NLP: usize>(self) -> RandHexStr<L, RP, NLP> {
RandHexStr
}
}
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
/// Randon string, with fix length and given charset.
///
/// # Generic Parameters
///
/// - `L`: The length of the string. Default is 32.
///
/// Notice: must make sure each u8 within the slice is valid
/// single byte UTF-8 char.
///
/// If the charset is `0123456789abcdef`, [`RandHexStr`] is recommended and 4~6x
/// faster than this (when feature `feat-random-fast` enabled).
pub struct RandStr<'r, const L: usize = 32>(&'r [u8]);
impl<const L: usize> StringExtT for RandStr<'_, L> {
fn push_to_string(self, string: &mut Vec<u8>) {
if self.0.is_empty() {
return;
}
string.extend(
rand::thread_rng()
.sample_iter(Slice::new(self.0).unwrap())
.take(L),
)
}
}
impl<'r> RandStr<'r> {
#[inline]
/// Create a new [`RandStr`] and generate random string with length
/// setting by `L`.
pub const fn with_charset_default(charset: &'r [u8]) -> Self {
Self(charset)
}
}
impl<'r, const L: usize> RandStr<'r, L> {
#[inline]
/// Create a new [`RandStr`] and generate random string with length
/// setting by `L`.
pub const fn with_charset(charset: &'r [u8]) -> Self {
Self(charset)
}
#[inline]
/// Set `L`.
pub const fn with_l<const NL: usize>(self) -> RandStr<'r, NL> {
RandStr(self.0)
}
}