tags:

views:

536

answers:

3

What module/library do you use to generate uuid?

+3  A: 

from http://github.com/travis/erlang-uuid

-module(uuid).
-export([v4/0, to_string/1, get_parts/1]).
-import(random).

v4() ->
    v4(random:uniform(math:pow(2, 48)) - 1, random:uniform(math:pow(2, 12)) - 1, random:uniform(math:pow(2, 32)) - 1, random:uniform(math:pow(2, 30)) - 1).
v4(R1, R2, R3, R4) ->
    <<R1:48, 4:4, R2:12, 2:2, R3:32, R4: 30>>.
to_string(U) ->
    lists:flatten(io_lib:format("~8.16.0b-~4.16.0b-~4.16.0b-~2.16.0b~2.16.0b-~12.16.0b", get_parts(U))).

get_parts(<<TL:32, TM:16, THV:16, CSR:8, CSL:8, N:48>>) ->
    [TL, TM, THV, CSR, CSL, N].
Tzury Bar Yochay
I cannot execute v4():2> uuid:v4().** exception error: no function clause matching random:uniform(281474976710656.0) in function uuid:v4/0
sinnus
filed a bug for you ;-)http://github.com/travis/erlang-uuid/issues/#issue/1
Tzury Bar Yochay
There is not much point in recalculating math:pow(2, 48) all the time anyway, it could simply be replaced with 16#FFFFFFFFFFFF. The others similarly.
Zed
@sinnus check out this commit, this was speedy indeed http://github.com/travis/erlang-uuid/issues/#issue/1
Tzury Bar Yochay
Thank you! But I have found another solution from couch_db.
sinnus
would be nice if you post it here since this page tops google search for "erlang uuid"
Tzury Bar Yochay
Erlang uuid generator from couchdb: http://svn.apache.org/viewvc/couchdb/trunk/src/couchdb/couch_uuids.erl
sinnus
Why do you import random if you use random:uniform? You don't need to do that in Erlang.
I GIVE TERRIBLE ADVICE
+1  A: 

Why did you use round(math:pow(2, 48))? I think that 1 bsl 48 will work more quickly and code will not lose understanding.

razumyan
+3  A: 

Uuid generator from couchdb: http://svn.apache.org/viewvc/couchdb/trunk/src/couchdb/couch%5Fuuids.erl

sinnus