1
0
forked from 0ad/0ad

Replace boost::uniform_real to avoid OOS caused by changes in behaviour between Boost versions

This was SVN commit r11857.
This commit is contained in:
Ykkrosh 2012-05-13 23:40:06 +00:00
parent 09414078fd
commit 2ee9981d99

View File

@ -439,6 +439,22 @@ JSBool ProfileStop(JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* vp)
// Math override functions: // Math override functions:
// boost::uniform_real is apparently buggy in Boost pre-1.47 - for integer generators
// it returns [min,max], not [min,max). The bug was fixed in 1.47.
// We need consistent behaviour, so manually implement the correct version:
static double generate_uniform_real(boost::rand48& rng, double min, double max)
{
while (true)
{
double n = (double)(rng() - rng.min());
double d = (double)(rng.max() - rng.min()) + 1.0;
ENSURE(d > 0 && n >= 0 && n <= d);
double r = n / d * (max - min) + min;
if (r < max)
return r;
}
}
JSBool Math_random(JSContext* cx, uintN UNUSED(argc), jsval* vp) JSBool Math_random(JSContext* cx, uintN UNUSED(argc), jsval* vp)
{ {
// Grab the RNG that was hidden in our slot // Grab the RNG that was hidden in our slot
@ -447,9 +463,7 @@ JSBool Math_random(JSContext* cx, uintN UNUSED(argc), jsval* vp)
return JS_FALSE; return JS_FALSE;
boost::rand48* rng = static_cast<boost::rand48*>(JSVAL_TO_PRIVATE(rngp)); boost::rand48* rng = static_cast<boost::rand48*>(JSVAL_TO_PRIVATE(rngp));
// TODO: is the double generation sufficiently deterministic for us? double r = generate_uniform_real(*rng, 0.0, 1.0);
boost::uniform_real<double> dist;
double r = dist(*rng);
jsval rv; jsval rv;
if (!JS_NewNumberValue(cx, r, &rv)) if (!JS_NewNumberValue(cx, r, &rv))