diff --git a/libc/test/src/sys/random/linux/getrandom_test.cpp b/libc/test/src/sys/random/linux/getrandom_test.cpp --- a/libc/test/src/sys/random/linux/getrandom_test.cpp +++ b/libc/test/src/sys/random/linux/getrandom_test.cpp @@ -6,6 +6,7 @@ // //===----------------------------------------------------------------------===// +#include "src/__support/CPP/array.h" #include "src/errno/libc_errno.h" #include "src/math/fabs.h" #include "src/sys/random/getrandom.h" @@ -13,53 +14,41 @@ #include "test/UnitTest/Test.h" TEST(LlvmLibcGetRandomTest, InvalidFlag) { - using __llvm_libc::testing::ErrnoSetterMatcher::Fails; - static constexpr size_t SIZE = 256; - char data[SIZE]; - libc_errno = 0; - ASSERT_THAT(__llvm_libc::getrandom(data, SIZE, -1), Fails(EINVAL)); + __llvm_libc::cpp::array buffer; libc_errno = 0; + ASSERT_THAT(__llvm_libc::getrandom(buffer.data(), buffer.size(), -1), + __llvm_libc::testing::ErrnoSetterMatcher::Fails(EINVAL)); } TEST(LlvmLibcGetRandomTest, InvalidBuffer) { - using __llvm_libc::testing::ErrnoSetterMatcher::Fails; - - libc_errno = 0; - ASSERT_THAT(__llvm_libc::getrandom(nullptr, 65536, 0), Fails(EFAULT)); libc_errno = 0; + ASSERT_THAT(__llvm_libc::getrandom(nullptr, 65536, 0), + __llvm_libc::testing::ErrnoSetterMatcher::Fails(EFAULT)); } TEST(LlvmLibcGetRandomTest, ReturnsSize) { - static constexpr size_t SIZE = 8192; - uint8_t buf[SIZE]; - for (size_t i = 0; i < SIZE; ++i) { + __llvm_libc::cpp::array buffer; + for (size_t i = 0; i < buffer.size(); ++i) { // Without GRND_RANDOM set this should never fail. - ASSERT_EQ(__llvm_libc::getrandom(buf, i, 0), static_cast(i)); + ASSERT_EQ(__llvm_libc::getrandom(buffer.data(), i, 0), + static_cast(i)); } } -TEST(LlvmLibcGetRandomTest, PiEstimation) { - static constexpr size_t LIMIT = 10000000; - static constexpr double PI = 3.14159265358979; +TEST(LlvmLibcGetRandomTest, CheckValue) { + // Probability of picking one particular value amongst 256 possibilities a + // hundred times in a row is (1/256)^100 = 1.49969681e-241. + __llvm_libc::cpp::array buffer; - auto generator = []() { - uint16_t data; - __llvm_libc::getrandom(&data, sizeof(data), 0); - return data; - }; + for (char &c : buffer) + c = 0; - auto sample = [&]() { - auto x = static_cast(generator()) / 65536.0; - auto y = static_cast(generator()) / 65536.0; - return x * x + y * y < 1.0; - }; + __llvm_libc::getrandom(buffer.data(), buffer.size(), 0); - double counter = 0; - for (size_t i = 0; i < LIMIT; ++i) { - if (sample()) { - counter += 1.0; - } - } - counter = counter / LIMIT * 4.0; - ASSERT_TRUE(__llvm_libc::fabs(counter - PI) < 0.1); + bool all_zeros = true; + for (char c : buffer) + if (c != 0) + all_zeros = false; + + ASSERT_FALSE(all_zeros); }