Generates a random number from [0, range), using a Linear Congruential Generator (LCG). Crashes if 'range' is 0 or greater than kMaxRange.
| 1818 | // Congruential Generator (LCG). Crashes if 'range' is 0 or greater |
| 1819 | // than kMaxRange. |
| 1820 | UInt32 Random::Generate(UInt32 range) { |
| 1821 | // These constants are the same as are used in glibc's rand(3). |
| 1822 | // Use wider types than necessary to prevent unsigned overflow diagnostics. |
| 1823 | state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange; |
| 1824 | |
| 1825 | GTEST_CHECK_(range > 0) |
| 1826 | << "Cannot generate a number in the range [0, 0)."; |
| 1827 | GTEST_CHECK_(range <= kMaxRange) |
| 1828 | << "Generation of a number in [0, " << range << ") was requested, " |
| 1829 | << "but this can only generate numbers in [0, " << kMaxRange << ")."; |
| 1830 | |
| 1831 | // Converting via modulus introduces a bit of downward bias, but |
| 1832 | // it's simple, and a linear congruential generator isn't too good |
| 1833 | // to begin with. |
| 1834 | return state_ % range; |
| 1835 | } |
| 1836 | |
| 1837 | // GTestIsInitialized() returns true iff the user has initialized |
| 1838 | // Google Test. Useful for catching the user mistake of not initializing |