leveled/src/leveled_rand.erl

59 lines
1.1 KiB
Erlang
Raw Normal View History

%% 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,
uniform/1,
seed/0,
rand_bytes/1
]).
-include_lib("eunit/include/eunit.hrl").
%%%===================================================================
%%% New (r19+) rand style functions
%%%===================================================================
-ifndef(old_rand).
2017-07-31 21:15:19 +02:00
uniform() ->
rand:uniform().
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().
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).
-endif.
-ifdef(TEST).
rand_test() ->
?assertMatch(true, uniform() < 1).
-endif.