quickwit_common/rand.rs
1// Copyright (C) 2021 Quickwit, Inc.
2//
3// Quickwit is offered under the AGPL v3.0 and as commercial software.
4// For commercial licensing, contact us at hello@quickwit.io.
5//
6// AGPL:
7// This program is free software: you can redistribute it and/or modify
8// it under the terms of the GNU Affero General Public License as
9// published by the Free Software Foundation, either version 3 of the
10// License, or (at your option) any later version.
11//
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU Affero General Public License for more details.
16//
17// You should have received a copy of the GNU Affero General Public License
18// along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20use rand::distributions::Alphanumeric;
21use rand::Rng;
22
23/// Appends a random suffix composed of a hyphen and five random alphanumeric characters.
24pub fn append_random_suffix(string: &str) -> String {
25 let rng = rand::thread_rng();
26 let slug: String = rng
27 .sample_iter(&Alphanumeric)
28 .take(5)
29 .map(char::from)
30 .collect();
31 format!("{}-{}", string, slug)
32}
33
34#[cfg(test)]
35mod tests {
36 use super::append_random_suffix;
37
38 #[test]
39 fn test_append_random_suffix() -> anyhow::Result<()> {
40 let randomized = append_random_suffix("");
41 let mut chars = randomized.chars();
42 assert_eq!(chars.next(), Some('-'));
43 assert_eq!(chars.clone().count(), 5);
44 assert!(chars.all(|ch| ch.is_ascii_alphanumeric()));
45 Ok(())
46 }
47}