~ubuntu-branches/ubuntu/trusty/aria2/trusty-proposed

« back to all changes in this revision

Viewing changes to src/SimpleRandomizer.cc

  • Committer: Package Import Robot
  • Author(s): Kartik Mistry
  • Date: 2013-12-16 18:41:03 UTC
  • mfrom: (2.5.21 sid)
  • Revision ID: package-import@ubuntu.com-20131216184103-xzah3019zwut429g
Tags: 1.18.1-1
New upstream release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
38
38
#include <unistd.h>
39
39
#include <cstdlib>
40
40
#include <cassert>
 
41
#include <cstring>
41
42
 
42
43
#include "a2time.h"
43
44
 
56
57
void SimpleRandomizer::init()
57
58
{
58
59
#ifndef __MINGW32__
59
 
  srandom(time(nullptr)^getpid());
 
60
  // Just in case std::random_device() is fixed, add time and pid too.
 
61
  eng_.seed(std::random_device()()^time(nullptr)^getpid());
60
62
#endif // !__MINGW32__
61
63
}
62
64
 
76
78
#endif // __MINGW32__
77
79
}
78
80
 
79
 
long int SimpleRandomizer::getRandomNumber()
 
81
long int SimpleRandomizer::getRandomNumber(long int to)
80
82
{
 
83
  assert(to > 0);
81
84
#ifdef __MINGW32__
82
85
  int32_t val;
83
86
  BOOL r = CryptGenRandom(cryProvider_, sizeof(val),
88
91
  } else if(val < 0) {
89
92
    val = -val;
90
93
  }
91
 
  return val;
92
 
#else // !__MINGW32__
93
 
  return random();
94
 
#endif // !__MINGW32__
95
 
}
96
 
 
97
 
long int SimpleRandomizer::getMaxRandomNumber()
98
 
{
99
 
#ifdef __MINGW32__
100
 
  return INT32_MAX;
101
 
#else // !__MINGW32__
102
 
  // TODO Warning: The maximum value of random() in some sytems (e.g.,
103
 
  // Solaris and openbsd) is (2**31)-1.
104
 
  return RAND_MAX;
105
 
#endif // !__MINGW32__
106
 
}
107
 
 
108
 
long int SimpleRandomizer::getRandomNumber(long int to)
109
 
{
110
 
  return getRandomNumber() % to;
 
94
  return val % to;
 
95
#else // !__MINGW32__
 
96
  return std::uniform_int_distribution<long int>(0, to - 1)(eng_);
 
97
#endif // !__MINGW32__
111
98
}
112
99
 
113
100
long int SimpleRandomizer::operator()(long int to)
115
102
  return getRandomNumber(to);
116
103
}
117
104
 
 
105
void SimpleRandomizer::getRandomBytes(unsigned char *buf, size_t len)
 
106
{
 
107
#ifdef __MINGW32__
 
108
  if (!CryptGenRandom(cryProvider_, len, (PBYTE)buf)) {
 
109
    throw std::bad_alloc();
 
110
  }
 
111
#else
 
112
  uint32_t val;
 
113
  size_t q = len / sizeof(val);
 
114
  size_t r = len % sizeof(val);
 
115
  auto gen = std::bind(std::uniform_int_distribution<uint32_t>
 
116
                       (0, std::numeric_limits<uint32_t>::max()),
 
117
                       eng_);
 
118
  for(; q > 0; --q) {
 
119
    val = gen();
 
120
    memcpy(buf, &val, sizeof(val));
 
121
    buf += sizeof(val);
 
122
  }
 
123
  val = gen();
 
124
  memcpy(buf, &val, r);
 
125
#endif
 
126
}
 
127
 
118
128
} // namespace aria2