2017-07-31 20:20:39 +02:00
|
|
|
%% Generalized random module that offers a backwards compatible API
|
|
|
|
%% around some of the changes in rand, crypto and for time units.
|
|
|
|
|
|
|
|
-module(leveled_rand).
|
|
|
|
|
|
|
|
%% API
|
|
|
|
-export([
|
2017-07-31 21:15:19 +02:00
|
|
|
uniform/0,
|
2017-07-31 20:20:39 +02:00
|
|
|
uniform/1,
|
|
|
|
seed/0,
|
|
|
|
rand_bytes/1
|
|
|
|
]).
|
|
|
|
|
2017-09-15 15:10:04 +01:00
|
|
|
|
|
|
|
-include_lib("eunit/include/eunit.hrl").
|
|
|
|
|
2017-07-31 20:20:39 +02:00
|
|
|
%%%===================================================================
|
|
|
|
%%% New (r19+) rand style functions
|
|
|
|
%%%===================================================================
|
|
|
|
-ifndef(old_rand).
|
2017-07-31 21:15:19 +02:00
|
|
|
uniform() ->
|
|
|
|
rand:uniform().
|
|
|
|
|
2017-07-31 20:20:39 +02:00
|
|
|
uniform(N) ->
|
|
|
|
rand:uniform(N).
|
|
|
|
|
|
|
|
seed() ->
|
|
|
|
ok.
|
|
|
|
|
|
|
|
rand_bytes(Size) ->
|
|
|
|
crypto:strong_rand_bytes(Size).
|
|
|
|
|
|
|
|
-else.
|
|
|
|
%%%===================================================================
|
|
|
|
%%% Old (r18) random style functions
|
|
|
|
%%%===================================================================
|
2017-07-31 21:15:19 +02:00
|
|
|
uniform() ->
|
|
|
|
random:uniform().
|
|
|
|
|
2017-07-31 20:20:39 +02:00
|
|
|
uniform(N) ->
|
|
|
|
random:uniform(N).
|
|
|
|
|
|
|
|
seed() ->
|
|
|
|
SW = os:timestamp(),
|
|
|
|
random:seed(erlang:phash2(self()), element(2, SW), element(3, SW)).
|
|
|
|
|
|
|
|
rand_bytes(Size) ->
|
2017-08-01 11:55:05 +02:00
|
|
|
crypto:rand_bytes(Size).
|
2017-07-31 20:20:39 +02:00
|
|
|
|
|
|
|
-endif.
|
2017-09-15 15:10:04 +01:00
|
|
|
|
|
|
|
|
|
|
|
-ifdef(TEST).
|
|
|
|
|
|
|
|
rand_test() ->
|
|
|
|
?assertMatch(true, uniform() < 1).
|
|
|
|
|
|
|
|
-endif.
|