X-Git-Url: http://demsky.eecs.uci.edu/git/?a=blobdiff_plain;f=folly%2FRandom.cpp;h=fcebfde9f208ba8df0a0c5eaf6d18bea4b97ae5f;hb=82b788f506cb45e44921c42337efb93e4bfe3656;hp=1398bd08df9987b04072845b9ff9f7c91fce3df1;hpb=6019aaaa140e5280812c0ecf69a1a1ec3d4af523;p=folly.git diff --git a/folly/Random.cpp b/folly/Random.cpp index 1398bd08..fcebfde9 100644 --- a/folly/Random.cpp +++ b/folly/Random.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "folly/Random.h" +#include #include #include @@ -23,18 +23,19 @@ #include #include -#include "folly/File.h" -#include "folly/FileUtil.h" +#include +#include namespace folly { namespace { -// Keep it open for the duration of the program -File randomDevice("/dev/urandom"); - void readRandomDevice(void* data, size_t size) { - PCHECK(readFull(randomDevice.fd(), data, size) == size); + // Keep the random device open for the duration of the program. + static int randomFd = ::open("/dev/urandom", O_RDONLY); + PCHECK(randomFd >= 0); + auto bytesRead = readFull(randomFd, data, size); + PCHECK(bytesRead >= 0 && size_t(bytesRead) == size); } class BufferedRandomDevice { @@ -91,16 +92,18 @@ void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) { ptr_ += size; } -ThreadLocal bufferedRandomDevice; } // namespace void Random::secureRandom(void* data, size_t size) { + static ThreadLocal bufferedRandomDevice; bufferedRandomDevice->get(data, size); } -folly::ThreadLocalPtr -ThreadLocalPRNG::localInstance; +ThreadLocalPRNG::ThreadLocalPRNG() { + static folly::ThreadLocal localInstance; + local_ = localInstance.get(); +} class ThreadLocalPRNG::LocalInstancePRNG { public: @@ -109,12 +112,6 @@ class ThreadLocalPRNG::LocalInstancePRNG { Random::DefaultGenerator rng; }; -ThreadLocalPRNG::LocalInstancePRNG* ThreadLocalPRNG::initLocal() { - auto ret = new LocalInstancePRNG; - localInstance.reset(ret); - return ret; -} - uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) { return local->rng(); }