Skip to content

Commit

Permalink
modernize some "random" methods (#17)
Browse files Browse the repository at this point in the history
* replace algorithms with "std::ranges" algorithms

* add more random tests
  • Loading branch information
annihilatorq authored Oct 17, 2024
1 parent 3689ecd commit 46d04c1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
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);
}

0 comments on commit 46d04c1

Please sign in to comment.