Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / test / src / stdlib / rand_test.cpp
blob7934dc16aa461a87f79f4c3d5546c1ce11fe9f72
1 //===-- Unittests for rand ------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "src/stdlib/rand.h"
10 #include "src/stdlib/srand.h"
11 #include "test/UnitTest/Test.h"
13 #include <stddef.h>
14 #include <stdlib.h>
16 TEST(LlvmLibcRandTest, UnsetSeed) {
17 static int vals[1000];
19 for (size_t i = 0; i < 1000; ++i) {
20 int val = LIBC_NAMESPACE::rand();
21 ASSERT_GE(val, 0);
22 ASSERT_LE(val, RAND_MAX);
23 vals[i] = val;
26 // FIXME: The GPU implementation cannot initialize the seed correctly.
27 #ifndef LIBC_TARGET_ARCH_IS_GPU
28 // The C standard specifies that if 'srand' is never called it should behave
29 // as if 'srand' was called with a value of 1. If we seed the value with 1 we
30 // should get the same sequence as the unseeded version.
31 LIBC_NAMESPACE::srand(1);
32 for (size_t i = 0; i < 1000; ++i)
33 ASSERT_EQ(LIBC_NAMESPACE::rand(), vals[i]);
34 #endif
37 TEST(LlvmLibcRandTest, SetSeed) {
38 const unsigned int SEED = 12344321;
39 LIBC_NAMESPACE::srand(SEED);
40 const size_t NUM_RESULTS = 10;
41 int results[NUM_RESULTS];
42 for (size_t i = 0; i < NUM_RESULTS; ++i) {
43 results[i] = LIBC_NAMESPACE::rand();
44 ASSERT_GE(results[i], 0);
45 ASSERT_LE(results[i], RAND_MAX);
48 // If the seed is set to the same value, it should give the same sequence.
49 LIBC_NAMESPACE::srand(SEED);
51 for (size_t i = 0; i < NUM_RESULTS; ++i) {
52 int val = LIBC_NAMESPACE::rand();
53 EXPECT_EQ(results[i], val);