Cbeam
Loading...
Searching...
No Matches
generators.hpp
Go to the documentation of this file.
1/*
2Copyright (c) 2025 acrion innovations GmbH
3Authors: Stefan Zipproth, s.zipproth@acrion.ch
4
5This file is part of Cbeam, see https://github.com/acrion/cbeam and https://cbeam.org
6
7Cbeam is offered under a commercial and under the AGPL license.
8For commercial licensing, contact us at https://acrion.ch/sales. For AGPL licensing, see below.
9
10AGPL licensing:
11
12Cbeam is free software: you can redistribute it and/or modify
13it under the terms of the GNU Affero General Public License as published by
14the Free Software Foundation, either version 3 of the License, or
15(at your option) any later version.
16
17Cbeam is distributed in the hope that it will be useful,
18but WITHOUT ANY WARRANTY; without even the implied warranty of
19MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20GNU Affero General Public License for more details.
21
22You should have received a copy of the GNU Affero General Public License
23along with Cbeam. If not, see <https://www.gnu.org/licenses/>.
24*/
25
26#pragma once
27
28#include <random> // for std::mt19937, std::random_device, std::uniform_int_distribution
29#include <string> // for std::string
30
32{
40 inline std::mt19937& default_generator()
41 {
44 thread_local static std::mt19937 gen{std::random_device{}()};
45 return gen;
46 }
47
52 inline std::size_t random_number(const std::size_t n, std::mt19937& gen = default_generator())
53 {
54 std::uniform_int_distribution<std::size_t> dist(0, n - 1);
55 return dist(gen);
56 }
57
67 inline std::string random_string(std::string::size_type length, std::mt19937& gen = default_generator())
68 {
69 static auto& chrs = "0123456789"
70 "abcdefghijklmnopqrstuvwxyz"
71 "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
72
73 thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2);
74
75 std::string s;
76
77 s.reserve(length);
78
79 while (length--)
80 {
81 s += chrs[pick(gen)];
82 }
83
84 return s;
85 }
86}
Collects random number generation tools for multithreaded environments. It includes a default thread-...
Definition generators.hpp:32
std::mt19937 & default_generator()
Returns a reference to a thread-local std::mt19937 random number generator.
Definition generators.hpp:40
std::size_t random_number(const std::size_t n, std::mt19937 &gen=default_generator())
Returns a random number in the range [0, n-1].
Definition generators.hpp:52
std::string random_string(std::string::size_type length, std::mt19937 &gen=default_generator())
Generates a random string of specified length.
Definition generators.hpp:67