ruby-changes:42895
From: nobu <ko1@a...>
Date: Tue, 10 May 2016 14:49:33 +0900 (JST)
Subject: [ruby-changes:42895] nobu:r54969 (trunk): random.c: reuse bits
nobu 2016-05-10 15:46:09 +0900 (Tue, 10 May 2016) New Revision: 54969 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=54969 Log: random.c: reuse bits * random.c (random_ulong_limited): reduce calling bytes methods by reusing dropped bits. Modified files: trunk/random.c Index: random.c =================================================================== --- random.c (revision 54968) +++ random.c (revision 54969) @@ -991,9 +991,21 @@ random_ulong_limited(VALUE obj, rb_rando https://github.com/ruby/ruby/blob/trunk/random.c#L991 { if (!limit) return 0; if (!rnd) { - unsigned long val, mask = make_mask(limit); + const int w = sizeof(limit) * CHAR_BIT - nlz_long(limit); + const int n = w > 32 ? sizeof(unsigned long) : sizeof(uint32_t); + const unsigned long mask = ~(~0UL << w); + const unsigned long full = ~(~0UL << n * CHAR_BIT); + unsigned long val, bits = 0, rest = 0; do { - obj_random_bytes(obj, &val, sizeof(unsigned long)); + if (mask & ~rest) { + union {uint32_t u32; unsigned long ul;} buf; + obj_random_bytes(obj, &buf, n); + rest = full; + bits = (n == sizeof(uint32_t)) ? buf.u32 : buf.ul; + } + val = bits; + bits >>= w; + rest >>= w; val &= mask; } while (limit < val); return val; -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/