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 //===----------------------------------------------------------------------===//
8
9 #include "src/stdlib/rand.h"
10 #include "src/stdlib/srand.h"
11 #include "test/UnitTest/Test.h"
12
13 #include <stddef.h>
14
TEST(LlvmLibcRandTest,UnsetSeed)15 TEST(LlvmLibcRandTest, UnsetSeed) {
16 static int vals[1000];
17
18 for (size_t i = 0; i < 1000; ++i) {
19 int val = LIBC_NAMESPACE::rand();
20 ASSERT_GE(val, 0);
21 ASSERT_LE(val, RAND_MAX);
22 vals[i] = val;
23 }
24
25 // The C standard specifies that if 'srand' is never called it should behave
26 // as if 'srand' was called with a value of 1. If we seed the value with 1 we
27 // should get the same sequence as the unseeded version.
28 LIBC_NAMESPACE::srand(1);
29 for (size_t i = 0; i < 1000; ++i)
30 ASSERT_EQ(LIBC_NAMESPACE::rand(), vals[i]);
31 }
32
TEST(LlvmLibcRandTest,SetSeed)33 TEST(LlvmLibcRandTest, SetSeed) {
34 const unsigned int SEED = 12344321;
35 LIBC_NAMESPACE::srand(SEED);
36 const size_t NUM_RESULTS = 10;
37 int results[NUM_RESULTS];
38 for (size_t i = 0; i < NUM_RESULTS; ++i) {
39 results[i] = LIBC_NAMESPACE::rand();
40 ASSERT_GE(results[i], 0);
41 ASSERT_LE(results[i], RAND_MAX);
42 }
43
44 // If the seed is set to the same value, it should give the same sequence.
45 LIBC_NAMESPACE::srand(SEED);
46
47 for (size_t i = 0; i < NUM_RESULTS; ++i) {
48 int val = LIBC_NAMESPACE::rand();
49 EXPECT_EQ(results[i], val);
50 }
51 }
52