src/rng

Source   Edit  

Procs

proc rand(dig: int): int {....raises: [OSError, ValueError], tags: [], forbids: [].}
A function that generates an integer A replacement function for rand() that is actually cryptographically secure. The final integer will always be between 1 to X (where X is the argument to the number)

Example:

echo "The dice returns... ", $rand(6) 
assert rand(5) < 6; # This is true since rand(5) returns a number between 1 and 5.
Source   Edit  
proc randch(letters: openArray[char] = defaultAsciiTable): char {.
    ...raises: [OSError, ValueError], tags: [], forbids: [].}
Returns a random character Source   Edit  
proc randint(limit: int): int {....raises: [OSError, ValueError], tags: [],
                                forbids: [].}
A function that generates an integer, limit is how many digits should be in the final string. ie. 10 generates a string that is 10 digits long.

Example:

assert randint(1) < 10 # The number return is at least 1 digit long, so its lower than 10.
Source   Edit  
proc randstr(length: int = 16; table: openArray[char] = defaultAsciiTable): string {.
    ...raises: [OSError, ValueError], tags: [], forbids: [].}
Returns a random string, A function to generate a safe random string.

Example:

echo "Your magical string is the following: ", randstr()
assert randstr(length = 20).len() == 20
Source   Edit  
proc sample(a: string): char {....raises: [OSError, ValueError], tags: [],
                               forbids: [].}
Returns a random character from a string

Example:

let magicalString = "Magic!"
echo "Your magical character from the magical string is ", sample(magicalString)
assert sample(magicalString) in magicalString
Source   Edit  
proc sample[T](a: openArray[T]): T
Returns a random element from an array.

Example:

let array = @["Jack", "Kate", "Adam", "Julie"]
echo "Your magic name is ", sample(array), "!"
assert sample(array) in array
Source   Edit  
proc uuidv4(): string {....raises: [OSError], tags: [], forbids: [].}

Generates a UUID (version 4). This type of UUID is completely random.

This implementation is based on nim-uuid4 by Matt Cooper (@vtbassmatt on GitHub)

Example:

echo uuidv4()

# Statistically unlikely to fail
assert uuidv4() != uuidv4()
Source   Edit