xref: /llvm-project/libc/test/src/stdlib/rand_test.cpp (revision 33bdb53d864e3e244d8fd5649062f17b7d4c958d)
138b6f58eSMichael Jones //===-- Unittests for rand ------------------------------------------------===//
238b6f58eSMichael Jones //
338b6f58eSMichael Jones // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
438b6f58eSMichael Jones // See https://llvm.org/LICENSE.txt for license information.
538b6f58eSMichael Jones // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
638b6f58eSMichael Jones //
738b6f58eSMichael Jones //===----------------------------------------------------------------------===//
838b6f58eSMichael Jones 
938b6f58eSMichael Jones #include "src/stdlib/rand.h"
1038b6f58eSMichael Jones #include "src/stdlib/srand.h"
11af1315c2SSiva Chandra Reddy #include "test/UnitTest/Test.h"
1238b6f58eSMichael Jones 
1338b6f58eSMichael Jones #include <stddef.h>
1438b6f58eSMichael Jones 
1538b6f58eSMichael Jones TEST(LlvmLibcRandTest, UnsetSeed) {
16ef169f57SJoseph Huber   static int vals[1000];
17ef169f57SJoseph Huber 
1838b6f58eSMichael Jones   for (size_t i = 0; i < 1000; ++i) {
19*b6bc9d72SGuillaume Chatelet     int val = LIBC_NAMESPACE::rand();
2038b6f58eSMichael Jones     ASSERT_GE(val, 0);
2138b6f58eSMichael Jones     ASSERT_LE(val, RAND_MAX);
22ef169f57SJoseph Huber     vals[i] = val;
2338b6f58eSMichael Jones   }
24ef169f57SJoseph Huber 
25ef169f57SJoseph Huber   // The C standard specifies that if 'srand' is never called it should behave
26ef169f57SJoseph Huber   // as if 'srand' was called with a value of 1. If we seed the value with 1 we
27ef169f57SJoseph Huber   // should get the same sequence as the unseeded version.
28*b6bc9d72SGuillaume Chatelet   LIBC_NAMESPACE::srand(1);
29ef169f57SJoseph Huber   for (size_t i = 0; i < 1000; ++i)
30*b6bc9d72SGuillaume Chatelet     ASSERT_EQ(LIBC_NAMESPACE::rand(), vals[i]);
3138b6f58eSMichael Jones }
3238b6f58eSMichael Jones 
3338b6f58eSMichael Jones TEST(LlvmLibcRandTest, SetSeed) {
3438b6f58eSMichael Jones   const unsigned int SEED = 12344321;
35*b6bc9d72SGuillaume Chatelet   LIBC_NAMESPACE::srand(SEED);
3638b6f58eSMichael Jones   const size_t NUM_RESULTS = 10;
3738b6f58eSMichael Jones   int results[NUM_RESULTS];
3838b6f58eSMichael Jones   for (size_t i = 0; i < NUM_RESULTS; ++i) {
39*b6bc9d72SGuillaume Chatelet     results[i] = LIBC_NAMESPACE::rand();
4038b6f58eSMichael Jones     ASSERT_GE(results[i], 0);
4138b6f58eSMichael Jones     ASSERT_LE(results[i], RAND_MAX);
4238b6f58eSMichael Jones   }
4338b6f58eSMichael Jones 
4438b6f58eSMichael Jones   // If the seed is set to the same value, it should give the same sequence.
45*b6bc9d72SGuillaume Chatelet   LIBC_NAMESPACE::srand(SEED);
4638b6f58eSMichael Jones 
4738b6f58eSMichael Jones   for (size_t i = 0; i < NUM_RESULTS; ++i) {
48*b6bc9d72SGuillaume Chatelet     int val = LIBC_NAMESPACE::rand();
4938b6f58eSMichael Jones     EXPECT_EQ(results[i], val);
5038b6f58eSMichael Jones   }
5138b6f58eSMichael Jones }
52