aboutsummaryrefslogtreecommitdiff
path: root/src/guid.erl
blob: 4c3fc155e898267d4c621a04678668e940f1bd3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
%% @author Guido Günther <agx@sigxcpu.org>
%% @copyright 2013 godiug.net
%%
%%  This library is free software; you can redistribute it and/or
%%  modify it under the terms of the GNU Lesser General Public
%%  License as published by the Free Software Foundation; either
%%  version 3 of the License, or (at your option) any later version.
%%
%%  This library is distributed in the hope that it will be useful,
%%  but WITHOUT ANY WARRANTY; without even the implied warranty of
%%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%%  Lesser General Public License for more details.
%%
%%  You should have received a copy of the GNU Lesser General Public
%%  License along with this library.  If not, see
%%  <http://www.gnu.org/licenses/>.
%%
%% @doc Simple v4 uuid generator

-module(guid).
-export([v4/0,
	 v4string/0,
	 unparse/1,
	 version/1]).

%% @doc generate a version 4 uuid as bin
v4() ->
    << D1:32, D2:16, D3:16, D4:64 >> = crypto:rand_bytes(16),
    << D1:32, D2:16, 4:4, D3:12, D4:64 >>.

%% @doc generate a version 4 uuid as string
v4string() ->
    unparse(v4()).

%% @doc convert a uuid from bin to string
unparse(UUID) ->
    lists:flatten(
      io_lib:format("~8.16.0b-"
                    "~4.16.0b-"
                    "~4.16.0b-"
                    "~2.16.0b~2.16.0b-"
                    "~12.16.0b", parts(UUID))).

%% @doc get a uuid's version number
version(<< _:48, Version:4, _:76 >>) ->
    Version.

%% @private
% Return the parts of the uuid as per rfc4122:
% time_low (32), time_mid (16), time_hi_and_version (16)
% clock_seq_hi_and_reseved (8), clock_seq_low(8), node (48)
parts(<< TL:32, TM:16, THV:16, CSHR:8, CSL:8, N:48 >>) ->
    [TL, TM, THV, CSHR, CSL, N].