Merge pull request #17020 from seandewar/vim-8.1.2342

vim-patch:8.1.{2342,2343,2356,2357},8.2.0233: `rand` and `srand`
This commit is contained in:
Sean Dewar 2022-02-05 15:30:09 +00:00 committed by GitHub
commit f68d25737f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 247 additions and 0 deletions

View File

@ -325,6 +325,7 @@ pumvisible() Number whether popup menu is visible
pyeval({expr}) any evaluate |Python| expression pyeval({expr}) any evaluate |Python| expression
py3eval({expr}) any evaluate |python3| expression py3eval({expr}) any evaluate |python3| expression
pyxeval({expr}) any evaluate |python_x| expression pyxeval({expr}) any evaluate |python_x| expression
rand([{expr}]) Number get pseudo-random number
range({expr} [, {max} [, {stride}]]) range({expr} [, {max} [, {stride}]])
List items from {expr} to {max} List items from {expr} to {max}
readdir({dir} [, {expr}]) List file names in {dir} selected by {expr} readdir({dir} [, {expr}]) List file names in {dir} selected by {expr}
@ -441,6 +442,7 @@ spellsuggest({word} [, {max} [, {capital}]])
split({expr} [, {pat} [, {keepempty}]]) split({expr} [, {pat} [, {keepempty}]])
List make |List| from {pat} separated {expr} List make |List| from {pat} separated {expr}
sqrt({expr}) Float square root of {expr} sqrt({expr}) Float square root of {expr}
srand([{expr}]) List get seed for |rand()|
stdioopen({dict}) Number open stdio in a headless instance. stdioopen({dict}) Number open stdio in a headless instance.
stdpath({what}) String/List returns the standard path(s) for {what} stdpath({what}) String/List returns the standard path(s) for {what}
str2float({expr} [, {quoted}]) Float convert String to Float str2float({expr} [, {quoted}]) Float convert String to Float
@ -5529,6 +5531,23 @@ range({expr} [, {max} [, {stride}]]) *range()*
< <
Can also be used as a |method|: > Can also be used as a |method|: >
GetExpr()->range() GetExpr()->range()
<
rand([{expr}]) *rand()*
Return a pseudo-random Number generated with an xoshiro128**
algorithm using seed {expr}. The returned number is 32 bits,
also on 64 bits systems, for consistency.
{expr} can be initialized by |srand()| and will be updated by
rand(). If {expr} is omitted, an internal seed value is used
and updated.
Examples: >
:echo rand()
:let seed = srand()
:echo rand(seed)
:echo rand(seed) % 16 " random number 0 - 15
<
Can also be used as a |method|: >
seed->rand()
< <
*readdir()* *readdir()*
readdir({directory} [, {expr}]) readdir({directory} [, {expr}])
@ -7178,6 +7197,23 @@ sqrt({expr}) *sqrt()*
Can also be used as a |method|: > Can also be used as a |method|: >
Compute()->sqrt() Compute()->sqrt()
srand([{expr}]) *srand()*
Initialize seed used by |rand()|:
- If {expr} is not given, seed values are initialized by
reading from /dev/urandom, if possible, or using time(NULL)
a.k.a. epoch time otherwise; this only has second accuracy.
- If {expr} is given it must be a Number. It is used to
initialize the seed values. This is useful for testing or
when a predictable sequence is intended.
Examples: >
:let seed = srand()
:let seed = srand(userinput)
:echo rand(seed)
<
Can also be used as a |method|: >
userinput->srand()
stdioopen({opts}) *stdioopen()* stdioopen({opts}) *stdioopen()*
With |--headless| this opens stdin and stdout as a |channel|. With |--headless| this opens stdin and stdout as a |channel|.
May be called only once. See |channel-stdio|. stderr is not May be called only once. See |channel-stdio|. stderr is not

View File

@ -574,6 +574,7 @@ Test functions:
test_scrollbar() test_scrollbar()
test_setmouse() test_setmouse()
test_settime() test_settime()
test_srand_seed()
TUI: TUI:
*t_xx* *termcap-options* *t_AB* *t_Sb* *t_vb* *t_SI* *t_xx* *termcap-options* *t_AB* *t_Sb* *t_vb* *t_SI*

View File

@ -273,6 +273,7 @@ return {
pyeval={args=1, base=1, func="f_py3eval"}, pyeval={args=1, base=1, func="f_py3eval"},
pyxeval={args=1, base=1, func="f_py3eval"}, pyxeval={args=1, base=1, func="f_py3eval"},
perleval={args=1, base=1}, perleval={args=1, base=1},
rand={args={0, 1}, base=1},
range={args={1, 3}, base=1}, range={args={1, 3}, base=1},
readdir={args={1, 2}, base=1}, readdir={args={1, 2}, base=1},
readfile={args={1, 3}, base=1}, readfile={args={1, 3}, base=1},
@ -348,6 +349,7 @@ return {
spellsuggest={args={1, 3}, base=1}, spellsuggest={args={1, 3}, base=1},
split={args={1, 3}, base=1}, split={args={1, 3}, base=1},
sqrt={args=1, base=1, func="float_op_wrapper", data="&sqrt"}, sqrt={args=1, base=1, func="float_op_wrapper", data="&sqrt"},
srand={args={0, 1}, base=1},
stdpath={args=1}, stdpath={args=1},
str2float={args=1, base=1}, str2float={args=1, base=1},
str2list={args={1, 2}, base=1}, str2list={args={1, 2}, base=1},

View File

@ -22,6 +22,7 @@
#include "nvim/eval/encode.h" #include "nvim/eval/encode.h"
#include "nvim/eval/executor.h" #include "nvim/eval/executor.h"
#include "nvim/eval/funcs.h" #include "nvim/eval/funcs.h"
#include "nvim/eval/typval.h"
#include "nvim/eval/userfunc.h" #include "nvim/eval/userfunc.h"
#include "nvim/ex_cmds2.h" #include "nvim/ex_cmds2.h"
#include "nvim/ex_docmd.h" #include "nvim/ex_docmd.h"
@ -6978,6 +6979,162 @@ static void f_py3eval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
script_host_eval("python3", argvars, rettv); script_host_eval("python3", argvars, rettv);
} }
static void init_srand(uint32_t *const x)
FUNC_ATTR_NONNULL_ALL
{
#ifndef MSWIN
static int dev_urandom_state = NOTDONE; // FAIL or OK once tried
if (dev_urandom_state != FAIL) {
const int fd = os_open("/dev/urandom", O_RDONLY, 0);
struct {
union {
uint32_t number;
char bytes[sizeof(uint32_t)];
} contents;
} buf;
// Attempt reading /dev/urandom.
if (fd == -1) {
dev_urandom_state = FAIL;
} else {
buf.contents.number = 0;
if (read(fd, buf.contents.bytes, sizeof(uint32_t)) != sizeof(uint32_t)) {
dev_urandom_state = FAIL;
} else {
dev_urandom_state = OK;
*x = buf.contents.number;
}
os_close(fd);
}
}
if (dev_urandom_state != OK) {
// Reading /dev/urandom doesn't work, fall back to time().
#endif
*x = time(NULL);
#ifndef MSWIN
}
#endif
}
static inline uint32_t splitmix32(uint32_t *const x)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
{
uint32_t z = (*x += 0x9e3779b9);
z = (z ^ (z >> 16)) * 0x85ebca6b;
z = (z ^ (z >> 13)) * 0xc2b2ae35;
return z ^ (z >> 16);
}
static inline uint32_t shuffle_xoshiro128starstar(uint32_t *const x, uint32_t *const y,
uint32_t *const z, uint32_t *const w)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
{
#define ROTL(x, k) ((x << k) | (x >> (32 - k)))
const uint32_t result = ROTL(*y * 5, 7) * 9;
const uint32_t t = *y << 9;
*z ^= *x;
*w ^= *y;
*y ^= *z;
*x ^= *w;
*z ^= t;
*w = ROTL(*w, 11);
#undef ROTL
return result;
}
/// "rand()" function
static void f_rand(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
uint32_t result;
if (argvars[0].v_type == VAR_UNKNOWN) {
static uint32_t gx, gy, gz, gw;
static bool initialized = false;
// When no argument is given use the global seed list.
if (!initialized) {
// Initialize the global seed list.
uint32_t x;
init_srand(&x);
gx = splitmix32(&x);
gy = splitmix32(&x);
gz = splitmix32(&x);
gw = splitmix32(&x);
initialized = true;
}
result = shuffle_xoshiro128starstar(&gx, &gy, &gz, &gw);
} else if (argvars[0].v_type == VAR_LIST) {
list_T *const l = argvars[0].vval.v_list;
if (tv_list_len(l) != 4) {
goto theend;
}
typval_T *const tvx = TV_LIST_ITEM_TV(tv_list_find(l, 0L));
typval_T *const tvy = TV_LIST_ITEM_TV(tv_list_find(l, 1L));
typval_T *const tvz = TV_LIST_ITEM_TV(tv_list_find(l, 2L));
typval_T *const tvw = TV_LIST_ITEM_TV(tv_list_find(l, 3L));
if (tvx->v_type != VAR_NUMBER) {
goto theend;
}
if (tvy->v_type != VAR_NUMBER) {
goto theend;
}
if (tvz->v_type != VAR_NUMBER) {
goto theend;
}
if (tvw->v_type != VAR_NUMBER) {
goto theend;
}
uint32_t x = tvx->vval.v_number;
uint32_t y = tvy->vval.v_number;
uint32_t z = tvz->vval.v_number;
uint32_t w = tvw->vval.v_number;
result = shuffle_xoshiro128starstar(&x, &y, &z, &w);
tvx->vval.v_number = (varnumber_T)x;
tvy->vval.v_number = (varnumber_T)y;
tvz->vval.v_number = (varnumber_T)z;
tvw->vval.v_number = (varnumber_T)w;
} else {
goto theend;
}
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = (varnumber_T)result;
return;
theend:
semsg(_(e_invarg2), tv_get_string(&argvars[0]));
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = -1;
}
/// "srand()" function
static void f_srand(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
uint32_t x = 0;
tv_list_alloc_ret(rettv, 4);
if (argvars[0].v_type == VAR_UNKNOWN) {
init_srand(&x);
} else {
bool error = false;
x = tv_get_number_chk(&argvars[0], &error);
if (error) {
return;
}
}
tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
}
/// "perleval()" function /// "perleval()" function
static void f_perleval(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_perleval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{ {

View File

@ -0,0 +1,51 @@
" Tests for srand() and rand()
func Test_Rand()
let r = srand(123456789)
call assert_equal([1573771921, 319883699, 2742014374, 1324369493], r)
call assert_equal(4284103975, rand(r))
call assert_equal(1001954530, rand(r))
call assert_equal(2701803082, rand(r))
call assert_equal(2658065534, rand(r))
call assert_equal(3104308804, rand(r))
" Nvim does not support test_settime
" call test_settime(12341234)
let s = srand()
if !has('win32') && filereadable('/dev/urandom')
" using /dev/urandom
call assert_notequal(s, srand())
" else
" " using time()
" call assert_equal(s, srand())
" call test_settime(12341235)
" call assert_notequal(s, srand())
endif
" Nvim does not support test_srand_seed
" call test_srand_seed(123456789)
" call assert_equal(4284103975, rand())
" call assert_equal(1001954530, rand())
" call test_srand_seed()
if has('float')
call assert_fails('echo srand(1.2)', 'E805:')
endif
call assert_fails('echo srand([1])', 'E745:')
call assert_fails('echo rand("burp")', 'E475:')
call assert_fails('echo rand([1, 2, 3])', 'E475:')
call assert_fails('echo rand([[1], 2, 3, 4])', 'E475:')
call assert_fails('echo rand([1, [2], 3, 4])', 'E475:')
call assert_fails('echo rand([1, 2, [3], 4])', 'E475:')
call assert_fails('echo rand([1, 2, 3, [4]])', 'E475:')
" call test_settime(0)
endfunc
func Test_issue_5587()
call rand()
call garbagecollect()
call rand()
endfunc
" vim: shiftwidth=2 sts=2 expandtab