From 91e425587a0b9b5ac0d1005844c661fee2e2813b Mon Sep 17 00:00:00 2001 From: "Stephan T. Lavavej" Date: Tue, 27 Aug 2024 21:34:44 -0700 Subject: [PATCH] Avoid `rand()` in the legacy `tr1` test suite (#4921) --- tests/tr1/tests/algorithm/test.cpp | 18 +++++++++++------- tests/tr1/tests/memory2/test.cpp | 6 ++++-- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/tests/tr1/tests/algorithm/test.cpp b/tests/tr1/tests/algorithm/test.cpp index 78683be089..ca9ee9c9d3 100644 --- a/tests/tr1/tests/algorithm/test.cpp +++ b/tests/tr1/tests/algorithm/test.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include // FUNCTION OBJECTS @@ -294,15 +295,13 @@ void test_copy(char* first, char* last, char* dest) { // test copying template f CHECK_STR(array2, "aaxx"); } -CSTD size_t frand(CSTD size_t nmax) { // return random value in [0, nmax) - return CSTD rand() % nmax; -} - struct rand_gen { // uniform random number generator + STD mt19937 mt; + typedef CSTD size_t result_type; result_type operator()() { // get random value - return CSTD rand() & 0xfffff; + return mt() & 0xfffff; } static result_type(min)() { // get minimum value @@ -429,8 +428,13 @@ void test_mutate(char* first, char* last, char* dest) { // test mutating templat CHECK_STR(array, "ebgf"); STD random_shuffle(first, last); - CSTD size_t (*prand)(CSTD size_t) = &frand; - STD random_shuffle(first, last, prand); + + STD mt19937 mt; + auto rng_func = [&mt](CSTD size_t nmax) { // return random value in [0, nmax) + STD uniform_int_distribution dist{0, nmax - 1}; + return dist(mt); + }; + STD random_shuffle(first, last, rng_func); rand_gen urng; STD shuffle(first, last, urng); diff --git a/tests/tr1/tests/memory2/test.cpp b/tests/tr1/tests/memory2/test.cpp index c03407804a..99e2ff3bf6 100644 --- a/tests/tr1/tests/memory2/test.cpp +++ b/tests/tr1/tests/memory2/test.cpp @@ -7,7 +7,7 @@ #include "tdefs.h" #include #include -#include +#include #include #include @@ -15,6 +15,7 @@ using STD shared_ptr; using STD weak_ptr; using STD lock_guard; +using STD mt19937; using STD mutex; using STD thread; using STD vector; @@ -27,6 +28,7 @@ static shared_ptr sp; static mutex start_mtx; static void ctors() { // construct a gazillion shared and weak pointers + mt19937 mt; { // wait for access lock_guard lock(start_mtx); @@ -34,7 +36,7 @@ static void ctors() { // construct a gazillion shared and weak pointers for (int i = 0; i < NSETS; ++i) { for (int j = 0; j < NREPS; ++j) { - if (rand() % 2 != 0) { + if (mt() % 2 != 0) { shared_ptr sp0(sp); } else { weak_ptr wp0(sp);