rand: --seed implemented.

This commit is contained in:
Ole Tange 2020-03-17 20:18:59 +01:00
parent 0047319b1b
commit 60744cc445

View file

@ -10,7 +10,7 @@ rand - generate (pseudo-)random data
=head1 SYNOPSIS =head1 SYNOPSIS
B<rand> [-f FORMAT|--format FORMAT] [[I<from>] I<to>] B<rand> [-f FORMAT|--format FORMAT] [-s SEED|--seed SEED] [[I<from>] I<to>]
=head1 DESCRIPTION =head1 DESCRIPTION
@ -37,6 +37,13 @@ If I<from> is also given, numbers will be integers from I<from> to I<to>.
Format number using I<FORMAT>. I<FORMAT> follows B<printf>s specification. Format number using I<FORMAT>. I<FORMAT> follows B<printf>s specification.
=item B<--seed> I<SEED>
=item B<-s> I<SEED>
Use SEED for random number generator for reproducible numbers.
=back =back
@ -98,10 +105,16 @@ B<openssl>
=cut =cut
randdata() { randdata() {
# Generate random 8-bit data by AES encrypting /dev/zero with a # Generate random 8-bit data by AES encrypting /dev/zero
# random key if [ "$seed" == "" ] ; then
key=$(openssl rand -hex 16) # use a random key
iv=$(openssl rand -hex 16) key=$(openssl rand -hex 16)
iv=$(openssl rand -hex 16)
else
# use seed from --seed
key=$(echo "$seed" | openssl sha256 -hex | cut -d' ' -f2)
iv=$(echo "$seed" | openssl sha512 -hex | cut -d' ' -f2)
fi
< /dev/zero openssl enc -aes-128-ctr -K $key -iv $iv 2>/dev/null < /dev/zero openssl enc -aes-128-ctr -K $key -iv $iv 2>/dev/null
} }
export -f randdata export -f randdata
@ -131,6 +144,7 @@ fmt='%s\n'
while true; do while true; do
case "$1" in case "$1" in
-f | --fmt ) fmt="$2"; shift 2 ;; -f | --fmt ) fmt="$2"; shift 2 ;;
-s | --seed ) seed="$2"; shift 2 ;;
-D | --debug ) debug=true; shift ;; -D | --debug ) debug=true; shift ;;
-h | --help ) help=1; shift 2 ;; -h | --help ) help=1; shift 2 ;;
-- ) shift; break ;; -- ) shift; break ;;
@ -139,16 +153,32 @@ while true; do
done done
qfmt="$(parallel --shellquote --shellquote ::: "$fmt")" qfmt="$(parallel --shellquote --shellquote ::: "$fmt")"
if [ "$1" == "" ] ; then if [ "$seed" == "" ] ; then
# Boost performance by running 1 per CPU core if [ "$1" == "" ] ; then
eval parallel -u randdata ::: {1..$(parallel --number-of-threads)} # Boost performance by running 1 per CPU core
else eval parallel -u randdata ::: {1..$(parallel --number-of-threads)}
# $1 set => numerical
if [ "$2" == "" ] ; then
# 0 .. $1
eval parallel -N0 --lb randints 0 $1 "$qfmt" ::: {1..$(parallel --number-of-threads)}
else else
# $1 .. $2 # $1 set => numerical
eval parallel -N0 --lb randints $1 $2 "$qfmt" ::: {1..$(parallel --number-of-threads)} if [ "$2" == "" ] ; then
# 0 .. $1
eval parallel -N0 --lb randints 0 $1 "$qfmt" ::: {1..$(parallel --number-of-threads)}
else
# $1 .. $2
eval parallel -N0 --lb randints $1 $2 "$qfmt" ::: {1..$(parallel --number-of-threads)}
fi
fi
else
if [ "$1" == "" ] ; then
# Run a single instance
randdata
else
# $1 set => numerical
if [ "$2" == "" ] ; then
# 0 .. $1
randints 0 $1 "$fmt"
else
# $1 .. $2
randints $1 $2 "$fmt"
fi
fi fi
fi fi