clarify the documentation of builtin random

The random builtin command may or may not produce values with a truly
random distribution. So make the documentation reflect that reality. Also,
make the command consistent with similar shells (e.g., bash, zsh) which
produce a range of [0..32767].

Resolves issue #1272.
This commit is contained in:
Kurtis Rader 2015-12-28 20:31:12 -08:00 committed by ridiculousfish
parent bc3260402a
commit ef31aa94f8
2 changed files with 15 additions and 5 deletions

View file

@ -7,9 +7,19 @@ random [SEED]
\subsection random-description Description
`random` outputs a random number from 0 to 32766, inclusive.
`random` outputs a psuedo-random number from 0 to 32767, inclusive.
Even ignoring the very narrow range of values you should not assume
this produces truly random values within that range. Do not use the
value for any cryptographic purposes. Even if you're using it to, for
example, generate unique identifiers you should be careful about handling
collisions; i.e., the same random number appearing more than once in a
given fish instance.
If a `SEED` value is provided, it is used to seed the random number generator, and no output will be produced. This can be useful for debugging purposes, where it can be desirable to get the same random number sequence multiple times. If the random number generator is called without first seeding it, the current time will be used as the seed.
If a `SEED` value is provided, it is used to seed the random number
generator, and no output will be produced. This can be useful for debugging
purposes, where it can be desirable to get the same random number sequence
multiple times. If the random number generator is called without first
seeding it, the current time will be used as the seed.
\subsection random-example Example

View file

@ -2345,7 +2345,6 @@ static int builtin_random(parser_t &parser, io_streams_t &streams, wchar_t **arg
switch (argc-w.woptind)
{
case 0:
{
long res;
@ -2356,8 +2355,9 @@ static int builtin_random(parser_t &parser, io_streams_t &streams, wchar_t **arg
srand48_r(time(0), &seed_buffer);
}
lrand48_r(&seed_buffer, &res);
streams.out.append_format( L"%ld\n", labs(res%32767));
// The labs() shouldn't be necessary since lrand48 is supposed to
// return only positive integers but we're going to play it safe.
streams.out.append_format(L"%ld\n", labs(res % 32768));
break;
}