aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGuido Günther <agx@sigxcpu.org>2013-10-29 14:32:43 +0100
committerGuido Günther <agx@sigxcpu.org>2013-10-30 16:37:59 +0100
commit6af72ef686ecc1c29c18bd0cbfbdd91e4ade9b26 (patch)
treec210a173d70fc6f1bdff0e4e1e878b1e58b4967d /src
Initial commitHEADmaster
Diffstat (limited to 'src')
-rw-r--r--src/guid.app.src9
-rw-r--r--src/guid.erl55
2 files changed, 64 insertions, 0 deletions
diff --git a/src/guid.app.src b/src/guid.app.src
new file mode 100644
index 0000000..afb6108
--- /dev/null
+++ b/src/guid.app.src
@@ -0,0 +1,9 @@
+%%-*- mode: erlang -*-
+{application, guid,
+ [
+ {description, "Simple v4 uuid generator"},
+ {vsn, git},
+ {registered, []},
+ {applications, []},
+ {env, []}
+ ]}.
diff --git a/src/guid.erl b/src/guid.erl
new file mode 100644
index 0000000..4c3fc15
--- /dev/null
+++ b/src/guid.erl
@@ -0,0 +1,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].
+
+