From 6af72ef686ecc1c29c18bd0cbfbdd91e4ade9b26 Mon Sep 17 00:00:00 2001 From: Guido Günther Date: Tue, 29 Oct 2013 14:32:43 +0100 Subject: Initial commit --- src/guid.app.src | 9 +++++++++ src/guid.erl | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/guid.app.src create mode 100644 src/guid.erl (limited to 'src') 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 +%% @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 +%% . +%% +%% @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]. + + -- cgit v1.2.3