cloud_copy/generator.rs
1//! Utility for random alphanumeric string generation.
2
3use std::fmt;
4
5use rand::Rng as _;
6
7/// An alphanumeric string generator.
8///
9/// Every display of the generator will create a new random alphanumeric string.
10///
11/// By default, the displayed string will use all alphanumeric characters.
12///
13/// Use the alternate format (i.e. `{:#}`) to use only lowercase alphanumeric
14/// characters.
15#[derive(Clone, Copy)]
16pub struct Alphanumeric {
17 /// The length of the alphanumeric string.
18 length: usize,
19}
20
21impl Alphanumeric {
22 /// Creates a new alphanumeric string generator with the given string
23 /// length.
24 pub fn new(length: usize) -> Self {
25 Self { length }
26 }
27}
28
29impl Default for Alphanumeric {
30 fn default() -> Self {
31 Self { length: 12 }
32 }
33}
34
35impl fmt::Display for Alphanumeric {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 let lowercase = f.alternate();
38 for c in rand::rng()
39 .sample_iter(&rand::distr::Alphanumeric)
40 .take(self.length)
41 .map(|c| if lowercase { c.to_ascii_lowercase() } else { c })
42 {
43 write!(f, "{c}", c = c as char)?;
44 }
45
46 Ok(())
47 }
48}