Use std::ifstream instead of file descriptor for generateRandomDataUrandom()

Usually required random bytes are short, it is advantageous to use
std::ifstream which is buffered I/O rather than read() syscall.
pull/8/head
Tatsuhiro Tsujikawa 2012-01-08 01:21:42 +09:00
parent 46e59c4cc3
commit b6f8a3dbb3
1 changed files with 9 additions and 17 deletions

View File

@ -1265,18 +1265,10 @@ void generateRandomDataRandom(unsigned char* data, size_t length)
} // namespace
namespace {
void generateRandomDataUrandom(unsigned char* data, size_t length, int fd)
void generateRandomDataUrandom
(unsigned char* data, size_t length, std::ifstream& devUrand)
{
while(length > 0) {
ssize_t r;
while((r = read(fd, data, length)) == -1 && errno == EINTR);
if(r <= 0) {
generateRandomDataRandom(data, length);
return;
}
length -= r;
data += r;
}
devUrand.read(reinterpret_cast<char*>(data), length);
}
} // namespace
@ -1286,17 +1278,17 @@ void generateRandomData(unsigned char* data, size_t length)
generateRandomDataRandom(data, length);
#else // !__MINGW32__
static int method = -1;
static int fd;
static std::ifstream devUrand;
if(method == 0) {
generateRandomDataUrandom(data, length, fd);
generateRandomDataUrandom(data, length, devUrand);
} else if(method == 1) {
generateRandomDataRandom(data, length);
} else {
while((fd = open("/dev/urandom", O_RDONLY)) == -1 && errno == EINTR);
if(fd == -1) {
method = 1;
} else {
devUrand.open("/dev/urandom");
if(devUrand) {
method = 0;
} else {
method = 1;
}
generateRandomData(data, length);
}