Skip to content

Commit de35e22

Browse files
feat: Make number::integer support more integral types (#1052)
* Make number::integer support more integral types Instead of using std::uniform_int_distribution<I>, which only supports certain integral types, use std::uniform_int_distribution<[unsigned] long long>, and allow any integral type not larger than long long. * Run clang-format --------- Co-authored-by: Michał Cieślar <[email protected]>
1 parent ddd8fdd commit de35e22

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

include/faker-cxx/number.h

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <optional>
55
#include <random>
66
#include <stdexcept>
7+
#include <type_traits>
78

89
#include "faker-cxx/export.h"
910
#include "faker-cxx/generator.h"
@@ -17,7 +18,7 @@ namespace faker::number
1718
* @param min The minimum value of the range.
1819
* @param max The maximum value of the range.
1920
*
20-
* @tparam I the type of the generated number, must be an integral type (int, long, long long, etc.).
21+
* @tparam I the type of the generated number, must be an integral type whose size is not larger than sizeof(long long).
2122
*
2223
* @throws std::invalid_argument if min is greater than max.
2324
*
@@ -28,24 +29,29 @@ namespace faker::number
2829
* @endcode
2930
*/
3031
template <std::integral I>
32+
requires(sizeof(I) <= sizeof(long long))
3133
I integer(I min, I max)
3234
{
35+
// std::uniform_int_distribution only accepts certain types, so we use signed or unsigned long long and don't allow
36+
// larger types
37+
using LongLongType = std::conditional_t<std::is_unsigned_v<I>, unsigned long long, long long>;
38+
3339
if (min > max)
3440
{
3541
throw std::invalid_argument("Minimum value must be smaller than maximum value.");
3642
}
3743

3844
std::mt19937_64& pseudoRandomGenerator = getGenerator();
3945

40-
std::uniform_int_distribution<I> distribution(min, max);
46+
std::uniform_int_distribution<LongLongType> distribution(min, max);
4147

42-
return distribution(pseudoRandomGenerator);
48+
return static_cast<I>(distribution(pseudoRandomGenerator));
4349
}
4450

4551
/**
4652
* @brief Generates a random integer between 0 and the given maximum value, bounds included.
4753
*
48-
* @tparam I the type of the generated number, must be an integral type (int, long, long long, etc.).
54+
* @tparam I the type of the generated number, must be an integral type whose size is not larger than sizeof(long long).
4955
* @param max the maximum value of the range.
5056
*
5157
* @throws std::invalid_argument if min is greater than max.
@@ -59,6 +65,7 @@ I integer(I min, I max)
5965
* @endcode
6066
*/
6167
template <std::integral I>
68+
requires(sizeof(I) <= sizeof(long long))
6269
I integer(I max)
6370
{
6471
return integer<I>(static_cast<I>(0), max);

0 commit comments

Comments
 (0)