#FEATURE
authorStefan Vogel <sv@exept.de>
Mon, 14 Mar 2016 18:45:48 +0100
changeset 3751 56b00c8eea80
parent 3750 54c47e28047d
child 3752 5e635bc6be94
child 3753 23d5633e7499
#FEATURE class: RandomGenerator added: #nextLettersOrDigits: changed: #next #nextCharacters: #nextInteger 64-bit support
RandomGenerator.st
--- a/RandomGenerator.st	Mon Mar 14 18:42:00 2016 +0100
+++ b/RandomGenerator.st	Mon Mar 14 18:45:48 2016 +0100
@@ -1,5 +1,3 @@
-"{ Encoding: utf8 }"
-
 "
  COPYRIGHT (c) 2007 by eXept Software AG
               All Rights Reserved
@@ -227,7 +225,7 @@
 next
     "return the next random number in the range 0..1"
 
-    ^ self nextInteger / 16r3fffffff asFloat
+    ^ self nextInteger / Float maxSmallInteger
 
     "
      |r|
@@ -271,22 +269,22 @@
     "Modified: / 12.11.1999 / 17:22:01 / stefan"
 !
 
-nextCharacters:cnt
-    "get the next cnt printable characters.
-     We answer characters in the ascii range (codepoints 32 - 127)"
+nextCharacters:count
+    "get the next count printable characters.
+     We answer printable characters in the ascii range (codepoints 32 - 126)"
 
-    |bytes string|
+    |bytes string cnt "{ Class:SmallInteger }"|
 
+    cnt := count.
     bytes := self nextBytes:cnt.
     string := String new:cnt.
 
-    bytes keysAndValuesDo:[:eachIndex :eachByte|
-        string at:eachIndex put:(Character value:(eachByte \\ 95 + 32)).
+    1 to:cnt do:[:eachIndex|
+        string at:eachIndex put:(Character value:((bytes at:eachIndex) \\ 94 + 32)).
     ].
 
     ^ string
 
-
     "
       RandomGenerator new nextCharacters:8
     "
@@ -294,17 +292,20 @@
 
 nextInteger
     "return the next integral random number,
-     in the range 0 .. 16r3FFFFFFF."
+     in the range 0 .. 16r3FFFFFFF (32-bit)
+     or 0 .. 16r3FFFFFFFFFFFFFFF (64-bit)."
 
-    |res|
+    |res intSize|
+
+    intSize := SmallInteger maxBytes.
 
     RandFile == true ifTrue:[
-        ^ OperatingSystem randomBytesInto:4.
+        ^ OperatingSystem randomBytesInto:intSize.
     ].
 
-    res := self nextBytes:4.
-    ^ ((((((res at:1) bitAnd:16r3F) * 256) + (res at:2)) * 256) + (res at:3)) * 256 + (res at:4)
-
+    res := self nextBytes:intSize.
+    res at:intSize put:((res at:intSize) bitAnd:16r3F).
+    ^ res asIntegerMSB:false.
 
 
     "
@@ -373,6 +374,28 @@
     "
 
     "Created: / 11.11.1999 / 10:28:36 / stefan"
+!
+
+nextLettersOrDigits:count
+    "get the next count printable letters or digits [0-9A-Za-z]."
+
+    |bytes string cnt "{ Class:SmallInteger }"|
+
+    cnt := count.
+    bytes := self nextBytes:cnt.
+    string := String new:cnt.
+
+    1 to:cnt do:[:eachIndex|
+        string 
+            at:eachIndex 
+            put:('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' at:((bytes at:eachIndex) \\ 62 + 1)).
+    ].
+
+    ^ string
+
+    "
+      RandomGenerator new nextLettersOrDigits:40
+    "
 ! !
 
 !RandomGenerator methodsFor:'writing'!