From 107d022bcf8ffdcbe944d59ab47bcee515d374b4 Mon Sep 17 00:00:00 2001 From: Konovod Date: Thu, 24 Aug 2017 23:19:14 +0000 Subject: [PATCH] fixes initialization of ISAAC PRNG without explicit seed adds specs for such initialization --- spec/std/random/isaac_spec.cr | 4 ++++ spec/std/random/pcg32_spec.cr | 4 ++++ src/random/isaac.cr | 15 +++++++++------ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/spec/std/random/isaac_spec.cr b/spec/std/random/isaac_spec.cr index d35eac5b02f3..2854e6dd811d 100644 --- a/spec/std/random/isaac_spec.cr +++ b/spec/std/random/isaac_spec.cr @@ -345,4 +345,8 @@ describe "Random::ISAAC" do m.next_u.should eq(n) end end + + it "can be initialized without explicit seed" do + Random::ISAAC.new.should be_a Random::ISAAC + end end diff --git a/spec/std/random/pcg32_spec.cr b/spec/std/random/pcg32_spec.cr index b63d09e08e8d..a231749716fd 100644 --- a/spec/std/random/pcg32_spec.cr +++ b/spec/std/random/pcg32_spec.cr @@ -231,4 +231,8 @@ describe "Random::PCG32" do m1.jump(-10) m1.next_u.should eq m2.next_u end + + it "can be initialized without explicit seed" do + Random::PCG32.new.should be_a Random::PCG32 + end end diff --git a/src/random/isaac.cr b/src/random/isaac.cr index b6b32d726e1f..03b5f7a994bf 100644 --- a/src/random/isaac.cr +++ b/src/random/isaac.cr @@ -12,13 +12,16 @@ class Random::ISAAC private getter bb private getter cc - private def self.random_seeds - (uninitialized StaticArray(UInt32, 8)).tap do |seeds| - System::Random.random_bytes(seeds.to_slice) - end + private alias Seeds = StaticArray(UInt32, 8) + + private def random_seeds + result = uninitialized Seeds + result_slice = result.unsafe_as(StaticArray(UInt8, sizeof(Seeds))).to_slice + Crystal::System::Random.random_bytes(result_slice) + result end - def initialize(seeds = self.random_seeds) + def initialize(seeds = random_seeds) @rsl = StaticArray(UInt32, 256).new { 0_u32 } @mm = StaticArray(UInt32, 256).new { 0_u32 } @counter = 0 @@ -26,7 +29,7 @@ class Random::ISAAC init_by_array(seeds) end - def new_seed(seeds = self.random_seeds) + def new_seed(seeds = random_seeds) @aa = @bb = @cc = 0_u32 init_by_array(seeds) end