Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

modernize some "random" methods #17

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/lib/es3n1n/common/random.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ namespace rnd {
/// \param ptr pointer where it should write these bytes
/// \param size number of bytes to generate
inline void bytes(std::uint8_t* ptr, const std::size_t size) {
std::generate_n(ptr, size, []() -> std::uint8_t { return number<std::uint8_t>(); });
std::ranges::generate_n(ptr, size, []() -> std::uint8_t { return number<std::uint8_t>(); });
}

/// \brief Generate a number of bytes and return them as a vector
Expand All @@ -119,11 +119,11 @@ namespace rnd {
/// \tparam Rng Range type
/// \param range Range value (vector/array/anything)
/// \return reference to a random value from the range
template <std::ranges::range Rng>
[[nodiscard]] const std::ranges::range_value_t<Rng>& item(Rng&& range) {
auto it = std::ranges::begin(range);
std::advance(it, number<std::size_t>(static_cast<std::size_t>(0), //
static_cast<std::size_t>(std::ranges::distance(range) - 1)));
template <std::ranges::range Rng, typename RngValueT = std::ranges::range_value_t<Rng>>
[[nodiscard]] const RngValueT& item(Rng&& range) {
auto distance = std::ranges::distance(range);
auto generated_number = rnd::number<>(std::size_t(0), static_cast<std::size_t>(distance - 1));
auto it = std::ranges::next(std::ranges::begin(range), generated_number);
return *it;
}

Expand Down
7 changes: 7 additions & 0 deletions src/tests/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,11 @@ TEST(random, basics) {
EXPECT_EQ(rnd::number<uint32_t>(50, 100), 96);
EXPECT_EQ(rnd::number<uint32_t>(50, 100), 70);
EXPECT_EQ(rnd::number<uint32_t>(50, 100), 93);

std::vector<int> vec = {10, 20, 30, 40, 50};
EXPECT_EQ(rnd::item(vec), 10);

std::array<int, 5> arr = {100, 200, 300, 400, 500};
EXPECT_EQ(rnd::item(arr), 400);
EXPECT_EQ(rnd::item(std::span<int>(arr)), 200);
}