/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FOLLY_RANDOM_H_ #error This file may only be included from folly/Random.h #endif namespace folly { namespace detail { // Return the state size needed by RNG, expressed as a number of uint32_t // integers. Specialized for all templates specified in the C++11 standard. // For some (mersenne_twister_engine), this is exported as a state_size static // data member; for others, the standard shows formulas. template struct StateSize { // A sane default. using type = std::integral_constant; }; template struct StateSize> { using type = std::integral_constant; }; template struct StateSize> { // From the standard [rand.eng.lcong], this is ceil(log2(m) / 32) + 3, // which is the same as ceil(ceil(log2(m) / 32) + 3, and // ceil(log2(m)) <= std::numeric_limits::digits using type = std::integral_constant< size_t, (std::numeric_limits::digits + 31) / 32 + 3>; }; template struct StateSize> { // [rand.eng.sub]: r * ceil(w / 32) using type = std::integral_constant; }; template using StateSizeT = _t>; template struct SeedData { SeedData() { Random::secureRandom(seedData.data(), seedData.size() * sizeof(uint32_t)); } static constexpr size_t stateSize = StateSizeT::value; std::array seedData; }; } // namespace detail template void Random::seed(RNG& rng) { detail::SeedData sd; std::seed_seq s(std::begin(sd.seedData), std::end(sd.seedData)); rng.seed(s); } template auto Random::create() -> RNG { detail::SeedData sd; std::seed_seq s(std::begin(sd.seedData), std::end(sd.seedData)); return RNG(s); } } // namespace folly