diff --git random.c random.c index a1deecf..f754b76 100644 --- random.c +++ random.c @@ -304,6 +304,7 @@ int_pair_to_real_inclusive(uint32_t a, uint32_t b) } VALUE rb_cRandom; +static VALUE rand_default; #define id_minus '-' #define id_plus '+' static ID id_rand, id_bytes; @@ -905,6 +906,18 @@ rb_random_bytes(VALUE obj, long n) return bytes; } +/* + * call-seq: Random.bytes(size) -> a_string + * + * Returns a random binary string. The argument size specified the length of + * the result string. + */ +static VALUE +random_s_bytes(VALUE obj, VALUE len) +{ + return random_bytes(rand_default, len); +} + static VALUE range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp) { @@ -1372,7 +1385,7 @@ InitVM_Random(void) rb_define_method(rb_cRandom, "==", random_equal, 1); { - VALUE rand_default = TypedData_Wrap_Struct(rb_cRandom, &random_data_type, &default_rand); + rand_default = TypedData_Wrap_Struct(rb_cRandom, &random_data_type, &default_rand); rb_gc_register_mark_object(rand_default); /* Direct access to Ruby's Pseudorandom number generator (PRNG). */ rb_define_const(rb_cRandom, "DEFAULT", rand_default); @@ -1380,6 +1393,7 @@ InitVM_Random(void) rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1); rb_define_singleton_method(rb_cRandom, "rand", random_s_rand, -1); + rb_define_singleton_method(rb_cRandom, "bytes", random_s_bytes, 1); rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0); rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0); rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0); diff --git test/ruby/test_rand.rb test/ruby/test_rand.rb index 62efecb..55cbdab 100644 --- test/ruby/test_rand.rb +++ test/ruby/test_rand.rb @@ -347,10 +347,13 @@ END end def assert_random_bytes(r) + srand(0) assert_equal("", r.bytes(0)) + assert_equal("", Random.bytes(0)) assert_equal("\xAC".force_encoding("ASCII-8BIT"), r.bytes(1)) - assert_equal("/\xAA\xC4\x97u\xA6\x16\xB7\xC0\xCC".force_encoding("ASCII-8BIT"), - r.bytes(10)) + assert_equal("\xAC".force_encoding("ASCII-8BIT"), Random.bytes(1)) + assert_equal("/\xAA\xC4\x97u\xA6\x16\xB7\xC0\xCC".force_encoding("ASCII-8BIT"), r.bytes(10)) + assert_equal("/\xAA\xC4\x97u\xA6\x16\xB7\xC0\xCC".force_encoding("ASCII-8BIT"), Random.bytes(10)) end def test_random_range