Support read and write from blocking and non-blocking pipes and sockets
[folly.git] / folly / test / RandomTest.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/Random.h>
18
19 #include <glog/logging.h>
20 #include <gtest/gtest.h>
21
22 #include <algorithm>
23 #include <thread>
24 #include <vector>
25 #include <random>
26
27 using namespace folly;
28
29 TEST(Random, StateSize) {
30   using namespace folly::detail;
31
32   // uint_fast32_t is uint64_t on x86_64, w00t
33   EXPECT_EQ(sizeof(uint_fast32_t) / 4 + 3,
34             StateSize<std::minstd_rand0>::value);
35   EXPECT_EQ(624, StateSize<std::mt19937>::value);
36 #if FOLLY_HAVE_EXTRANDOM_SFMT19937
37   EXPECT_EQ(624, StateSize<__gnu_cxx::sfmt19937>::value);
38 #endif
39   EXPECT_EQ(24, StateSize<std::ranlux24_base>::value);
40 }
41
42 TEST(Random, Simple) {
43   uint32_t prev = 0, seed = 0;
44   for (int i = 0; i < 1024; ++i) {
45     EXPECT_NE(seed = randomNumberSeed(), prev);
46     prev = seed;
47   }
48 }
49
50 TEST(Random, FixedSeed) {
51   // clang-format off
52   struct ConstantRNG {
53     typedef uint32_t result_type;
54     result_type operator()() {
55       return 4; // chosen by fair dice roll.
56                 // guaranteed to be random.
57     }
58     static constexpr result_type min() {
59       return std::numeric_limits<result_type>::min();
60     }
61     static constexpr result_type max() {
62       return std::numeric_limits<result_type>::max();
63     }
64   };
65   // clang-format on
66
67   ConstantRNG gen;
68
69   // Pick a constant random number...
70   auto value = Random::rand32(10, gen);
71
72   // Loop to make sure it really is constant.
73   for (int i = 0; i < 1024; ++i) {
74     auto result = Random::rand32(10, gen);
75     EXPECT_EQ(value, result);
76   }
77 }
78
79 TEST(Random, MultiThreaded) {
80   const int n = 100;
81   std::vector<uint32_t> seeds(n);
82   std::vector<std::thread> threads;
83   for (int i = 0; i < n; ++i) {
84     threads.push_back(std::thread([i, &seeds] {
85       seeds[i] = randomNumberSeed();
86     }));
87   }
88   for (auto& t : threads) {
89     t.join();
90   }
91   std::sort(seeds.begin(), seeds.end());
92   for (int i = 0; i < n-1; ++i) {
93     EXPECT_LT(seeds[i], seeds[i+1]);
94   }
95 }