MLton.Random.seed

Stephen Weeks MLton@sourcelight.com
Tue, 26 Jun 2001 08:16:00 -0700


> You  mutation  lover: use Posix.IO.readVec and Pack32Little.subVec instead of
> Posix.IO.readArr and Pack32Little.subArr.

I meant to use the array stuff so I could avoid per call allocation.  My new
version does that.

> As to the exception to raise, I don't know.  For /dev/random, you might hang,
> but  you  shouldn't  get  back a short read.  For /dev/urandom, even the hang
> shouldn't happen.  If you get  a  short  result  back,  something  is  really
> insane.

I took a look and I am getting short reads from /dev/random.  It does also
hang.  So, I changed the code to the following.

      (* Linux specific.  Uses /dev/random and /dev/urandom to get a
       * random word.
       *)
      local
	 fun make (file, name) =
	    let
	       val buf = Word8Array.array (4, 0w0)
	    in
	       fn () =>
	       let
		  val fd =
		     let
			open Posix.FileSys
		     in
			openf (file, O_RDONLY, O.flags [])
		     end
		  fun loop rem =
		     let
			val n = Posix.IO.readArr (fd, {buf = buf,
						       i = 4 - rem,
						       sz = SOME rem})
			val _ = if n = 0
				   then (Posix.IO.close fd; raise Fail name)
				else ()
			val rem = rem - n
		     in
			if rem = 0
			   then ()
			else loop rem
		     end
		  val _ = loop 4
		  val _ = Posix.IO.close fd
	       in
		  Pack32Little.subArr (buf, 0)
	       end
	    end
      in
	 val seed = make ("/dev/random", "Random.seed")
	 val useed = make ("/dev/urandom", "Random.useed")
      end