Category talk:Wren-srandom

From Rosetta Code

Source code

/* Module "srandom.wren" */

import "io" for File

/*
    SRandom generates secure random integers from the /dev/urandom special file
    present on Linux or other Unix-like operating systems.
*/
class SRandom {
    // Returns an unsigned 32 bit integer between 0 and 4,294,967,295 inclusive.
    static int() {
        var n
        File.open("/dev/urandom") { |file|
            var b = file.readBytes(4).bytes.toList
            n = b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24
        }
        return n
    }

    // Returns an integer between start and end, including start but excluding end.
    static int(start, end) {
        if (!(start is Num && start.isInteger && start >= 0 && start < 4294967296)) {
            Fiber.abort("Start must be a non-negative 32 bit integer.")
        }
        if (!(end is Num && end.isInteger && end > 0 && end < 4294967296)) {
            Fiber.abort("End must be a positive 32 bit integer.")
        }
        if (start >= end) Fiber.abort("Start must be less than end.")
        return start + int() % (end - start)
    }

    // Returns an integer between 0 and end, including 0 but excluding end.
    static int(end) { int(0, end) }
}