!=========================================================================
! Copyright (C) VMware, Inc. 1986-2011.  All Rights Reserved.
!
! $Id: fastrandom.gs,v 1.7 2008-01-09 22:50:10 stever Exp $
!
! Superclass Hierarchy:
!   Stream, Object.
!
!=========================================================================

expectvalue %String
run
| cls |
cls := 
UserGlobals at:#FastRandom ifAbsent:[
  (Stream subclass: 'FastRandom'
    instVarNames: #( 'seed' 'last')
    classVars: #()
    poolDictionaries: #[]
    inDictionary: UserGlobals
    constraints: #[  ]
    instancesInvariant: false
    isModifiable: false) category: 'User Classes'
].
cls definition
%
removeallmethods FastRandom
removeallclassmethods FastRandom

category: 'For Documentation Installation only'
classmethod: FastRandom
installDocumentation

| doc txt |
doc := GsClassDocumentation newForClass: self.

txt := (GsDocText new) details:
'FastRandom is an implementation of a fast random number generator.  As a
 congruency modulus generator, its spectral qualities are somewhat limited, but
 it may be satisfactory for some applications.'.
doc documentClassWith: txt.

self description: doc.
%

category: 'accessing'
method: FastRandom
nextPut: anObject
	"Random numbers do not implement nextPut: so provide an
	error notification."

	^self shouldNotImplement
%
method: FastRandom
contents
	"Random numbers do not have a contents so provide
	an error notification."

	^self shouldNotImplement
%
method: FastRandom
flush
	"Random numbers do not need to flush."

	^self shouldNotImplement
%
category: 'testing'
method: FastRandom
atEnd
	"Returns false that the stream is not at an end."

	^false
%

category: 'Accessing'
method: FastRandom
seed

   "Return the value of the instance variable 'seed'."
   ^seed
%

!=========================================================================
category: 'Accessing'
method: FastRandom
next
	"Returns the next random number."

  ^ last := ((27181 * last) + 13849) bitAnd: 16rffff
%

category: 'accessing'
method: FastRandom
between: min and: max

   "Return a random value between min and max, inclusive"

  ^(self next \\ (max - min + 1)) + min
%

category: 'Instance Creation'
classmethod: FastRandom
new
	^self basicNew initialize.
%

category: 'Initialization'
method: FastRandom
seed: aSeed
  last := seed := aSeed.
%

category: 'Private'
method: FastRandom
initialize

  "Initialize an instance, seeded by the time of day"

  self seed: (System _timeMs \\ 524288000)
%

category: 'Testing'
classmethod: FastRandom
speed
       "Random speed will benchmark the efficiency of random number generation"

|rand|

rand := self new.

^(System millisecondsToRun: [ 10000 timesRepeat: [rand next]
  ]) / 10000.0
%

!=========================================================================
! Install the GsClassDocumentation

run
FastRandom installDocumentation.
(FastRandom class) removeCategory: 'For Documentation Installation only'.
%
