pax_global_header00006660000000000000000000000064133100434510014504gustar00rootroot0000000000000052 comment=cb02a2039a9b29dd2eef0446039c9c6e164df9ef erlang-uuid-0.5.2/000077500000000000000000000000001331004345100137245ustar00rootroot00000000000000erlang-uuid-0.5.2/.gitignore000066400000000000000000000000221331004345100157060ustar00rootroot00000000000000*.beam ebin/*.app erlang-uuid-0.5.2/CONTRIBUTORS000066400000000000000000000004241331004345100156040ustar00rootroot00000000000000Per Andersson Bip Thelin Iivari Äikäs Ryan Flynn William Cummings Gianni Gambetti Peter Hizalev Jean Rouge erlang-uuid-0.5.2/COPYING000066400000000000000000000167431331004345100147720ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. erlang-uuid-0.5.2/Emakefile000066400000000000000000000001071331004345100155270ustar00rootroot00000000000000{'src/*', [{outdir, "ebin"}, compressed, debug_info, strip ]}. erlang-uuid-0.5.2/Makefile000066400000000000000000000024571331004345100153740ustar00rootroot00000000000000#!/usr/bin/make -f APPFILE := uuid.app VERSION := $(shell sed -n -e '/vsn/ {s/.*,[[:blank:]]*"\([0-9][0-9.]*\)".*/\1/' \ -e 'p' -e '}' src/$(APPFILE).src) PREFIX ?= /usr ERL_ROOT := $(PREFIX)/lib/erlang LIBDIR := /lib DISTDIR := uuid-$(VERSION) BEAMFILES := $(wildcard ebin/*.beam) $(wildcard test/*.beam) DIALYZER_PLT := erlang-uuid.plt all: build build: ebin/$(APPFILE) erl -make ebin/$(APPFILE): src/$(APPFILE).src cp $< $@ clean: -rm -rf dist ebin/$(APPFILE) $(BEAMFILES) $(DIALYZER_PLT) $(DIALYZER_PLT): build dialyzer --add_to_plt -r ebin --output_plt $(DIALYZER_PLT) dialyzer: $(DIALYZER_PLT) dialyzer --plt $(DIALYZER_PLT) ebin/uuid.beam test: build erlc -W +debug_info +compressed +strip -o test/ test/*.erl erl -noshell -pa ebin -pa test -eval "uuid_tests:test()" -eval "init:stop()" dist: build # create dist tarball mkdir -p dist/$(DISTDIR)/ebin install -m0644 ebin/* dist/$(DISTDIR)/ebin (cd dist ; tar zcf $(DISTDIR).tar.gz $(DISTDIR) ) install: build # create dist directory and install files mkdir -p $(DESTDIR)$(ERL_ROOT)$(LIBDIR)/$(DISTDIR)/ebin install -m0644 ebin/* $(DESTDIR)$(ERL_ROOT)$(LIBDIR)/$(DISTDIR)/ebin uninstall: -rm -rf $(DESTDIR)$(ERL_ROOT)$(LIBDIR)/uuid-[0-9][0-9.]* .PHONY: all build clean dialyzer test install uninstall erlang-uuid-0.5.2/README000066400000000000000000000075211331004345100146110ustar00rootroot00000000000000ERLANG UUID =========== This module implements UUID v1, v3, v4, and v5 as of RFC 4122 (UUID variant 1 0). UUID v1 return a UUID generated by a timestamp and node id. UUID v3 return a UUID generated using MD5 and a given name within a namespace. UUID v4 return a UUID generated by a (pseudo) random number generator. UUID v5 return a UUID generated using SHA1 and a given name within a namespace. Source tracking available at http://github.com/avtobiff/erlang-uuid To clone the main developing repository invoke git clone https://github.com/avtobiff/erlang-uuid.git BUILD AND INSTALL ----------------- Build by invoking make Install to default $ERL_ROOT (/usr/lib/erlang) by invoking sudo make install Install to different $ERL_ROOT ($PREFIX/lib/erlang) by setting PREFIX sudo make PREFIX=/opt/erlang install Include in your own project using Rebar. Add this to your rebar.config {uuid, ".*", {git, "https://github.com/avtobiff/erlang-uuid.git", "master"}} LICENSE ------- Erlang UUID 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. Erlang UUID 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 Erlang UUID. If not, see . USE --- Example of usage 1> uuid:to_string(uuid:uuid1()). "f412e400-c445-1131-bdc6-03f9e757eb34" 2> uuid:to_string(uuid:uuid3(dns, "fqdn.example.com")). "06eaa791-8c2e-3b0d-8a07-c80979fd1b98" 3> uuid:to_string(uuid:uuid3(uuid:uuid4(), "my name")). "fcf82b93-aa5e-3d79-b95e-726420f89e1b" 4> uuid:to_string(uuid:uuid4()). "79f492f8-1337-4200-abcd-92bada1cacao" 5> uuid:to_string(uuid:uuid5(dns, "fqdn.example.com")). "8fd7fa87-4c20-5809-a1b0-e07f5c224f02" 6> uuid:to_string(uuid:uuid5(uuid:uuid4(), "my name")). "6ff58b11-e0b2-536c-b6be-bdccd38836a2" UUID v1 ------- UUID v1 uses the number of 100 nanosecond intervals since the west adopted the gregorian calendar and the node id IEEE 802 (MAC) address. It is hackishly implemented and improvements can be made. Room for improvement: * Timestamp resolution is one (1) second which should be improved. * Clock sequence is random (simulating state is always unavailable). UUID v3 UUID v5 ------- UUID v3 and UUID v5 uses MD5 and SHA1, respectivaly, to generate a UUID using a name and a namespace as initializer. Valid namespaces are the atoms: url, dns, oid, x500, nil or using a generated UUID either as a binary or as a UUID string representation. UUID v4 ------- UUID v4 uses randomness to create a UUID, the six version and variant bits are set all the other 122 bits are randomly generated. UTILITIES --------- There are several utility functions for introspection of UUIDs. It is possible to extract variant and version with the functions with the same names, both take a UUID binary or UUID string representation. There are several predicate functions that takes a UUID binary or UUID string representation and returns a thruth value. The predicate is_rfc4122/1 returns true if the UUID implements RFC 4122 (variant 1 0, version 1, 3, 4, and 5). The predicates is_vN/1, where N is either 1, 3, 4, or 5. Example usage: 1> uuid:version(uuid:uuid4()). 4 2> uuid:is_v1(uuid:uuid4()). false 3> uuid:is_v1(uuid:uuid1()). true 4> uuid:is_rfc4122(uuid:uuid4()). true 5> uuid:is_valid(uuid:uuid4()). true 6> uuid:is_valid(<<1:128>>). false Per Andersson Mon, 20 Feb 2012 21:01:47 +0100 erlang-uuid-0.5.2/ebin/000077500000000000000000000000001331004345100146415ustar00rootroot00000000000000erlang-uuid-0.5.2/ebin/.empty000066400000000000000000000000001331004345100157660ustar00rootroot00000000000000erlang-uuid-0.5.2/src/000077500000000000000000000000001331004345100145135ustar00rootroot00000000000000erlang-uuid-0.5.2/src/uuid.app.src000066400000000000000000000002421331004345100167470ustar00rootroot00000000000000{application, uuid, [{description, "Erlang UUID"}, {vsn, "0.5.2"}, {modules, [uuid]}, {registered, []}, {applications, [stdlib, crypto]}, {env, []}]}. erlang-uuid-0.5.2/src/uuid.erl000066400000000000000000000367121331004345100161760ustar00rootroot00000000000000%% ----------------------------------------------------------------------------- %% Copyright © 2010-2018 Per Andersson %% %% Erlang UUID 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. %% %% Erlang UUID 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 Erlang UUID. If not, see %% . %% ----------------------------------------------------------------------------- %% @author Per Andersson %% @copyright 2010-2018 Per Andersson %% 2012 Bip Thelin %% 2013 Ryan Flynn %% 2013 Iivari Äikäs %% 2013 William Cummings %% 2014 Gianni Gambetti %% 2015 Peter Hizalev %% 2017 Jean Rouge %% @doc %% Erlang UUID %% %% Currently implements UUID v1, v3, v4, and v5 as of RFC 4122. %% %% Example usage %%
%%      1> uuid:to_string(uuid:uuid1()).
%%      "f412e400-c445-1131-bdc6-03f9e757eb34"
%%      2> uuid:to_string(uuid:uuid3(dns, "fqdn.example.com")).
%%      "06eaa791-8c2e-3b0d-8a07-c80979fd1b98"
%%      3> uuid:to_string(uuid:uuid3(uuid:uuid4(), "my name")).
%%      "fcf82b93-aa5e-3d79-b95e-726420f89e1b"
%%      4> uuid:to_string(uuid:uuid4()).
%%      "79f492f8-1337-4200-abcd-92bada1cacao"
%%      5> uuid:to_string(uuid:uuid5(dns, "fqdn.example.com")).
%%      "8fd7fa87-4c20-5809-a1b0-e07f5c224f02"
%%      6> uuid:to_string(uuid:uuid5(uuid:uuid4(), "my name")).
%%      "6ff58b11-e0b2-536c-b6be-bdccd38836a2"
%% 
%% @end %% @reference See RFC 4122 %% for more information. %% ----------------------------------------------------------------------------- -module(uuid). -author('Per Andersson'). -include("uuid.hrl"). -export([get_node/0, to_binary/1, to_string/1, to_string/2, to_uuid_urn/1, uuid1/0, uuid1/2, uuid3/2, uuid4/0, uuid5/2, variant/1, version/1, is_v1/1, is_v3/1, is_v4/1, is_v5/1, is_valid/1, now_xor_pid/0]). %% The UUID types -type uuid() :: binary(). -type uuid_string() :: string(). -type urn() :: string(). -export_type([uuid/0, uuid_string/0, urn/0]). %% ============================================================================= %% UUID v1 %% ============================================================================= %% @doc Create a UUID v1 (timebased). -spec uuid1() -> uuid(). uuid1() -> %% FIXME Use random clock sequence for now ("state is unavailable"). uuid1(null, null). -spec uuid1(NodeArg::binary() | null, ClockSeqArg::binary() | null) -> uuid(). uuid1(NodeArg, ClockSeqArg) -> %% Get time, clock_seq and node <> = uuid1_time(), <> = uuid1_clockseq(ClockSeqArg), Node = uuid1_node(NodeArg), %% Compose UUIDv1 <>. %% @private %% @doc Get nanosecond timestamp. -spec uuid1_time() -> <<_:60>>. uuid1_time() -> %% Transform unix epoch to 100 nanosecond intervals since 15 October 1582 %% by adding offset to unix epoch and transforming microseconds epoch to %% nanoseconds. {MegaSeconds, Seconds, MicroSeconds} = os:timestamp(), UnixEpoch = (MegaSeconds * 1000000000000 + Seconds * 1000000 + MicroSeconds), Timestamp = ?nanosecond_intervals_offset + ?nanosecond_intervals_factor * UnixEpoch, <>. %% @private %% @doc Use ClockSeq if supplied otherwise Generate random clock sequence. -spec uuid1_clockseq(null | binary()) -> <<_:14>>. uuid1_clockseq(null) -> Rnd = random_uniform(now_xor_pid(), 2 bsl 14 - 1), <>; uuid1_clockseq(ClockSeqArg) -> <<_:14>> = ClockSeqArg. % make 14 bits wide %% @private %% @doc Get MAC address. -spec uuid1_node(null | binary()) -> binary(). uuid1_node(null) -> get_node(); uuid1_node(NodeArg) -> NodeArg. %% ============================================================================= %% UUID v3 %% ============================================================================= %% @doc Create a UUID v3 (name based, MD5 is hashing function) as a binary. %% Magic numbers are from Appendix C of the RFC 4122. -spec uuid3(NamespaceOrUuid::atom() | uuid_string() | uuid(), Name::string()) -> uuid(). uuid3(dns, Name) -> create_namebased_uuid(md5, list_to_binary([<<16#6ba7b8109dad11d180b400c04fd430c8:128>>, Name])); uuid3(url, Name) -> create_namebased_uuid(md5, list_to_binary([<<16#6ba7b8119dad11d180b400c04fd430c8:128>>, Name])); uuid3(oid, Name) -> create_namebased_uuid(md5, list_to_binary([<<16#6ba7b8129dad11d180b400c04fd430c8:128>>, Name])); uuid3(x500, Name) -> create_namebased_uuid(md5, list_to_binary([<<16#6ba7b8149dad11d180b400c04fd430c8:128>>, Name])); uuid3(nil, Name) -> create_namebased_uuid(md5, list_to_binary([<<0:128>>, Name])); uuid3(UuidStr, Name) when is_list(UuidStr) -> create_namebased_uuid(md5, list_to_binary([to_binary(UuidStr), Name])); uuid3(UuidBin, Name) when is_binary(UuidBin) -> create_namebased_uuid(md5, list_to_binary([UuidBin, Name])); uuid3(_, _) -> erlang:error(badarg). %% ============================================================================= %% UUID v4 %% ============================================================================= %% @doc Create a UUID v4 (random) as a binary -spec uuid4() -> uuid(). uuid4() -> % Set the four most significant bits (bits 12 through 15) of the % time_hi_and_version field to 0100, corresponding to version 4. % Set the two most significant bits (bits 6 and 7) of the % clock_seq_hi_and_reserved to zero and one, respectively. % Corresponding to variant 1 0. % Set all other bits pseudo-randomly chosen values % (as generated by caller). <> = crypto:strong_rand_bytes(16), <>. %% ============================================================================= %% UUID v5 %% ============================================================================= %% @doc Create a UUID v5 (name based, SHA1 is hashing function) as a binary. %% Magic numbers are from Appendix C of the RFC 4122. -spec uuid5(NamespaceOrUuid::atom() | uuid_string() | uuid(), Name::string()) -> uuid(). uuid5(dns, Name) -> create_namebased_uuid(sha1, list_to_binary([<<16#6ba7b8109dad11d180b400c04fd430c8:128>>, Name])); uuid5(url, Name) -> create_namebased_uuid(sha1, list_to_binary([<<16#6ba7b8119dad11d180b400c04fd430c8:128>>, Name])); uuid5(oid, Name) -> create_namebased_uuid(sha1, list_to_binary([<<16#6ba7b8129dad11d180b400c04fd430c8:128>>, Name])); uuid5(x500, Name) -> create_namebased_uuid(sha1, list_to_binary([<<16#6ba7b8149dad11d180b400c04fd430c8:128>>, Name])); uuid5(nil, Name) -> create_namebased_uuid(sha1, list_to_binary([<<0:128>>, Name])); uuid5(UuidStr, Name) when is_list(UuidStr) -> create_namebased_uuid(sha1, list_to_binary([to_binary(UuidStr), Name])); uuid5(UuidBin, Name) when is_binary(UuidBin) -> create_namebased_uuid(sha1, list_to_binary([UuidBin, Name])); uuid5(_, _) -> erlang:error(badarg). %% @private %% @doc Create a UUID v3 or v5 (name based) from binary, using MD5 or SHA1 %% respectively. -spec create_namebased_uuid(HashFunction::md5 | sha1, Data::binary()) -> uuid(). create_namebased_uuid(md5, Data) -> Md5 = crypto:hash(md5, Data), compose_namebased_uuid(?UUIDv3, Md5); create_namebased_uuid(sha1, Data) -> <> = crypto:hash(sha, Data), compose_namebased_uuid(?UUIDv5, <>). %% @private %% @doc Compose a namebased UUID (v3 or v5) with input hashed data. -spec compose_namebased_uuid(Version::3 | 5, Hash::binary()) -> uuid(). compose_namebased_uuid(Version, Hash) -> <> = Hash, <>. %% ============================================================================= %% Formatting functions %% ============================================================================= %% @doc Format UUID string from binary -spec to_string(Uuid::uuid()) -> uuid_string(). to_string(<<_:128>> = Uuid) -> to_string(pretty, Uuid); to_string(_) -> erlang:error(badarg). -spec to_string(simple | pretty, Uuid::uuid()) -> uuid_string(). to_string(pretty, <>) -> lists:flatten(io_lib:format( "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b", [U0, U1, U2, U3, U4])); to_string(simple, <>) -> lists:flatten(io_lib:format("~32.16.0b", [S])); to_string(_, _) -> erlang:error(badarg). %% @doc Create UUID URN from UUID binary or string. -spec to_uuid_urn(UuidOrUrn::uuid() | uuid_string()) -> urn(). to_uuid_urn([$u, $r, $n, $:, $u, $u, $i, $d, $: |_] = Urn) -> Urn; to_uuid_urn(<<_:128>> = Uuid) -> "urn:uuid:" ++ uuid:to_string(Uuid); to_uuid_urn(Uuid) when is_list(Uuid) -> "urn:uuid:" ++ Uuid. %% @doc Format UUID binary from string. -spec to_binary(UuidStr::uuid_string()) -> uuid(). to_binary(UuidStr) when is_list(UuidStr) -> case length(UuidStr) of 36 -> to_binary(pretty, UuidStr); 32 -> to_binary(simple, UuidStr); _ -> erlang:error(badarg) end; to_binary(_) -> erlang:error(badarg). %% @private -spec to_binary(simple | pretty, UuidStr::uuid_string()) -> uuid(). to_binary(simple, UuidStr) -> Num = hex_to_int(UuidStr), <>; to_binary(pretty, UuidStr) -> Parts = string:tokens(UuidStr, "$-"), [I0, I1, I2, I3, I4] = [hex_to_int(Part) || Part <- Parts], <>. %% ============================================================================= %% Helper functions %% ============================================================================= %% @private %% @doc Convert from hexadecimal digit represented as string to decimal. -spec hex_to_int(Hex::string()) -> integer(). hex_to_int(Hex) -> {ok, [D], []} = io_lib:fread("~16u", Hex), D. %% @doc Get node id (IEEE 802 (MAC) address). Create random node id if hardware %% address can't be found. -spec get_node() -> binary(). get_node() -> %% Get interfaces {ok, Ifs0} = inet:getifaddrs(), hwaddr_find(Ifs0). %% @private %% @doc Search interface config for hwaddr and return random if no hwaddr was %% found. -spec hwaddr_find([{string(), proplists:proplist()}]) -> binary(). hwaddr_find([{"lo", _IfConfig}|Rest]) -> %% Do not use loopback interface hwaddr_find(Rest); hwaddr_find([{_IfName, IfConfig}|Rest]) -> case lists:keyfind(hwaddr, 1, IfConfig) of {hwaddr, HwAddr} -> list_to_binary(HwAddr); false -> hwaddr_find(Rest) end; hwaddr_find(_) -> %% Generate random hwaddr as last resort hwaddr_random(). %% @private %% @doc Generate random MAC address -spec hwaddr_random() -> binary(). hwaddr_random() -> %% No interface, create random 48-bit number with bit 8 set to one. <> = crypto:strong_rand_bytes(6), %% Set 8 to 1 <>. %% @doc Return version for supplied UUID. -spec version(Uuid::uuid() | uuid_string()) -> integer(). version(<<_:128>> = Uuid) -> <<_:48, Version:4, _:76>> = Uuid, Version; version(UuidStr) when is_list(UuidStr) -> version(uuid:to_binary(UuidStr)); version(_) -> erlang:error(badarg). %% @doc Return variant for supplied UUID. -spec variant(Uuid::uuid() | uuid_string()) -> reserved_microsoft | reserved_ncs | resered_future | rfc4122. variant(<<_:64, 0:1, _:1, _:1, _:61>>) -> reserved_ncs; variant(<<_:64, 1:1, 0:1, _:1, _:61>>) -> rfc4122; variant(<<_:64, 1:1, 1:1, 0:1, _:61>>) -> reserved_microsoft; variant(<<_:64, 1:1, 1:1, 1:1, _:61>>) -> reserved_future; variant(UuidStr) when is_list(UuidStr) -> variant(uuid:to_binary(UuidStr)); variant(_) -> erlang:error(badarg). %% @doc Predicate for checking that supplied UUID is version 1. -spec is_v1(Uuid::uuid() | uuid_string()) -> true | false. is_v1(Uuid) -> ?UUIDv1 =:= version(Uuid). %% @doc Predicate for checking that supplied UUID is version 3. -spec is_v3(Uuid::uuid() | uuid_string()) -> true | false. is_v3(Uuid) -> ?UUIDv3 =:= version(Uuid). %% @doc Predicate for checking that supplied UUID is version 4. -spec is_v4(Uuid::uuid() | uuid_string()) -> true | false. is_v4(Uuid) -> ?UUIDv4 =:= version(Uuid). %% @doc Predicate for checking that supplied UUID is version 5. -spec is_v5(Uuid::uuid() | uuid_string()) -> true | false. is_v5(Uuid) -> ?UUIDv5 =:= version(Uuid). %% @doc Predicate for checking that supplied UUID is valid. -spec is_valid(Uuid::uuid() | uuid_string()) -> true | false. %% XXX special nil UUID is valid is_valid(<<0:128>>) -> true; is_valid(Uuid = <<_:128>>) -> is_valid(variant(Uuid), Uuid); is_valid(UuidStr) when is_list(UuidStr) -> is_valid(to_binary(UuidStr)); is_valid(_) -> erlang:error(badarg). %% @private %% @doc Predicate for checking that supplied UUID is valid, takes variant as %% argument and returns validity depending on UUID version. -spec is_valid(Variant::atom(), Uuid::uuid()) -> true | false. is_valid(rfc4122, Uuid) -> case version(Uuid) of ?UUIDv1 -> true; ?UUIDv3 -> true; ?UUIDv4 -> true; ?UUIDv5 -> true; _ -> false end; is_valid(_, _) -> false. %% @private %% @doc Utility function for getting random bytes and perform bitwise xor with %% pid. Used for random seed. -spec now_xor_pid() -> {pos_integer(), pos_integer(), pos_integer()}. now_xor_pid() -> PidSum = erlang:phash2(self()), <> = crypto:strong_rand_bytes(12), {N0 bxor PidSum, N1 bxor PidSum, N2 bxor PidSum}. %% @private %% @doc We try to use the newer `rand' module (over the older `random') %% if it's available; we cache the result for efficiency random_uniform(Seed, N) -> case application:get_env(uuid, random_uniform_fun) of {ok, RandomUniformFun} -> RandomUniformFun(Seed, N); undefined -> set_random_uniform_fun(), random_uniform(Seed, N) end. %% @private %% @see random_uniform/2. set_random_uniform_fun() -> Fun = case code:ensure_loaded(rand) of {module, rand} -> fun(Seed, N) -> rand:seed(exs1024, Seed), rand:uniform(N) end; {error, _} -> fun(Seed, N) -> %% using `erlang:apply/3' is a cheap way of avoiding %% deprecation compilation warnings in OTP >= 19.0 erlang:apply(random, seed, [Seed]), erlang:apply(random, uniform, [N]) end end, application:set_env(uuid, random_uniform_fun, Fun). erlang-uuid-0.5.2/src/uuid.hrl000066400000000000000000000033511331004345100161720ustar00rootroot00000000000000%% ----------------------------------------------------------------------------- %% Copyright © 2010-2018 Per Andersson %% %% Erlang UUID 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. %% %% Erlang UUID 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 Erlang UUID. If not, see %% . %% ----------------------------------------------------------------------------- %% @author Per Andersson %% @copyright 2010-2018 Per Andersson %% 2012 Bip Thelin %% 2013 Ryan Flynn %% 2013 Iivari Äikäs %% 2013 William Cummings %% 2014 Gianni Gambetti %% 2015 Peter Hizalev %% 2017 Jean Rouge %% @doc %% Erlang UUID %% %% Include file for types, definitions, and macros. %% @end %% ----------------------------------------------------------------------------- %% Variant, corresponds to variant 1 0 of RFC 4122. -define(VARIANT10, 2#10). %% For 100 nanosecond interval transformation in UUIDv1. %% Offset between 15 October 1582 and 1 January 1970 -define(nanosecond_intervals_offset, 122192928000000000). %% microseconds to nanoseconds -define(nanosecond_intervals_factor, 10). %% Version -define(UUIDv1, 1). -define(UUIDv3, 3). -define(UUIDv4, 4). -define(UUIDv5, 5). erlang-uuid-0.5.2/test/000077500000000000000000000000001331004345100147035ustar00rootroot00000000000000erlang-uuid-0.5.2/test/uuid_tests.erl000066400000000000000000000226331331004345100176050ustar00rootroot00000000000000%% ----------------------------------------------------------------------------- %% Copyright © 2010-2013 Per Andersson %% %% Erlang UUID 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. %% %% Erlang UUID 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 Erlang UUID. If not, see %% . %% ----------------------------------------------------------------------------- %% @author Per Andersson %% @copyright 2010-2013 Per Andersson %% @doc %% Erlang UUID %% %% HERE BE UUID TESTS %% @end %% ----------------------------------------------------------------------------- -module(uuid_tests). -author('Per Andersson'). -include_lib("eunit/include/eunit.hrl"). -include("../src/uuid.hrl"). uuid_binary_test() -> Uuid = uuid:uuid4(), %% UUID v1 NodeId = uuid:get_node(), ?assertMatch(<<_U0:48, ?UUIDv1:4, _U1:12, ?VARIANT10:2, _U2:14, NodeId/binary>>, uuid:uuid1()), NilNode = <<0:48>>, ClockSeq = <> = <<0:14>>, ?assertMatch(<<_U0:48, ?UUIDv1:4, _U1:12, ?VARIANT10:2, ClockSeqLow:8, ClockSeqHi:6, NilNode/binary>>, uuid:uuid1(NilNode, ClockSeq)), %% UUID v3 ?assertMatch(<<_U0:48, ?UUIDv3:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid3(dns, "fqdn.example.com")), ?assertEqual(uuid:uuid3(dns, "fqdn.example.com"), uuid:uuid3(dns, "fqdn.example.com")), ?assertMatch(<<_U0:48, ?UUIDv3:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid3(oid, "2.5.6")), ?assertEqual(uuid:uuid3(oid, "2.5.6"), uuid:uuid3(oid, "2.5.6")), ?assertMatch(<<_U0:48, ?UUIDv3:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid3(url, "http://fqdn.example.com/path")), ?assertEqual(uuid:uuid3(url, "http://fqdn.example.com/path"), uuid:uuid3(url, "http://fqdn.example.com/path")), ?assertMatch(<<_U0:48, ?UUIDv3:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid3(x500, "cn=John Doe, o=Acme, Inc., c=US")), ?assertEqual(uuid:uuid3(x500, "cn=John Doe, o=Acme, Inc., c=US"), uuid:uuid3(x500, "cn=John Doe, o=Acme, Inc., c=US")), ?assertMatch(<<_U0:48, ?UUIDv3:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid3(nil, "my own unique name")), ?assertEqual(uuid:uuid3(nil, "my own unique name"), uuid:uuid3(nil, "my own unique name")), ?assertMatch(<<_U0:48, ?UUIDv3:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid3(Uuid, "fqdn.example.com")), ?assertEqual(uuid:uuid3(Uuid, "fqdn.example.com"), uuid:uuid3(Uuid, "fqdn.example.com")), ?assertMatch(<<_U0:48, ?UUIDv3:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid3(uuid:to_string(Uuid), "fqdn.example.com")), ?assertEqual(uuid:uuid3(uuid:to_string(Uuid), "fqdn.example.com"), uuid:uuid3(uuid:to_string(Uuid), "fqdn.example.com")), %% UUID v4 ?assertMatch(<<_U0:48, ?UUIDv4:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid4()), %% UUID v5 ?assertMatch(<<_U0:48, ?UUIDv5:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid5(dns, "fqdn.example.com")), ?assertEqual(uuid:uuid5(dns, "fqdn.example.com"), uuid:uuid5(dns, "fqdn.example.com")), ?assertMatch(<<_U0:48, ?UUIDv5:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid5(oid, "2.5.6")), ?assertEqual(uuid:uuid5(oid, "2.5.6"), uuid:uuid5(oid, "2.5.6")), ?assertMatch(<<_U0:48, ?UUIDv5:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid5(url, "http://fqdn.example.com/path")), ?assertEqual(uuid:uuid5(url, "http://fqdn.example.com/path"), uuid:uuid5(url, "http://fqdn.example.com/path")), ?assertMatch(<<_U0:48, ?UUIDv5:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid5(x500, "cn=John Doe, o=Acme, Inc., c=US")), ?assertEqual(uuid:uuid5(x500, "cn=John Doe, o=Acme, Inc., c=US"), uuid:uuid5(x500, "cn=John Doe, o=Acme, Inc., c=US")), ?assertMatch(<<_U0:48, ?UUIDv5:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid5(nil, "my own unique name")), ?assertEqual(uuid:uuid5(nil, "my own unique name"), uuid:uuid5(nil, "my own unique name")), ?assertMatch(<<_U0:48, ?UUIDv5:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid5(Uuid, "fqdn.example.com")), ?assertEqual(uuid:uuid5(Uuid, "fqdn.example.com"), uuid:uuid5(Uuid, "fqdn.example.com")), ?assertMatch(<<_U0:48, ?UUIDv5:4, _U1:12, ?VARIANT10:2, _U2:62>>, uuid:uuid5(uuid:to_string(Uuid), "fqdn.example.com")), ?assertEqual(uuid:uuid5(uuid:to_string(Uuid), "fqdn.example.com"), uuid:uuid5(uuid:to_string(Uuid), "fqdn.example.com")). representation_test() -> Uuid1 = uuid:uuid1(), Uuid3 = uuid:uuid5(dns, "fqdn.example.com"), Uuid4 = uuid:uuid4(), Uuid5 = uuid:uuid5(dns, "fqdn.example.com"), ?assertMatch(Uuid1, uuid:to_binary(uuid:to_string(Uuid1))), ?assertMatch(Uuid3, uuid:to_binary(uuid:to_string(Uuid3))), ?assertMatch(Uuid4, uuid:to_binary(uuid:to_string(Uuid4))), ?assertMatch(Uuid5, uuid:to_binary(uuid:to_string(Uuid5))). conversion_test() -> SimpleUuid = "8fd7fa874c205809a1b0e07f5c224f02", PrettyUuid = "8fd7fa87-4c20-5809-a1b0-e07f5c224f02", ?assertMatch(PrettyUuid, uuid:to_string(uuid:uuid5(dns, "fqdn.example.com"))), ?assertMatch(PrettyUuid, uuid:to_string(pretty, uuid:uuid5(dns, "fqdn.example.com"))), ?assertMatch(SimpleUuid, uuid:to_string(simple, uuid:uuid5(dns, "fqdn.example.com"))), ?assertMatch(PrettyUuid, uuid:to_string(uuid:to_binary(SimpleUuid))), ?assertMatch(SimpleUuid, uuid:to_string(simple, uuid:to_binary(SimpleUuid))), ?assertMatch(PrettyUuid, uuid:to_string(pretty, uuid:to_binary(PrettyUuid))). exceptions_test() -> ?assertMatch(ok, try_badarg(to_binary, [0])), ?assertMatch(ok, try_badarg(to_string, [0])), ?assertMatch(ok, try_badarg(to_string, [0, 0])), ?assertMatch(ok, try_badarg(uuid3, [0, 0])), ?assertMatch(ok, try_badarg(uuid5, [0, 0])), ?assertMatch(ok, try_badarg(version, [0])). urn_test() -> UuidBin = uuid:uuid4(), UrnBin = uuid:to_uuid_urn(UuidBin), UuidStr = uuid:to_string(UuidBin), UrnStr = uuid:to_uuid_urn(UuidStr), [$u,$r,$n,$:,$u,$u,$i,$d,$:|UrnUuidBinStr] = UrnBin, ?assertMatch(UrnUuidBinStr, uuid:to_string(UuidBin)), [$u,$r,$n,$:,$u,$u,$i,$d,$:|UrnUuidStr] = UrnStr, ?assertMatch(UrnUuidStr, UuidStr), ?assertMatch(UrnUuidBinStr, UrnUuidStr), ?assertMatch(UrnBin, uuid:to_uuid_urn(UrnBin)). version_test() -> Uuid1 = uuid:uuid1(), Uuid3 = uuid:uuid3(nil, ""), Uuid4 = uuid:uuid4(), Uuid5 = uuid:uuid5(nil, ""), ?assertMatch(?UUIDv1, uuid:version(Uuid1)), ?assertMatch(?UUIDv3, uuid:version(Uuid3)), ?assertMatch(?UUIDv4, uuid:version(Uuid4)), ?assertMatch(?UUIDv5, uuid:version(Uuid5)), Uuids = [Uuid1, Uuid3, Uuid4, Uuid5], ?assertMatch([true, false, false, false], lists:map(fun uuid:is_v1/1, Uuids)), ?assertMatch([false, true, false, false], lists:map(fun uuid:is_v3/1, Uuids)), ?assertMatch([false, false, true, false], lists:map(fun uuid:is_v4/1, Uuids)), ?assertMatch([false, false, false, true], lists:map(fun uuid:is_v5/1, Uuids)), ?assertMatch([rfc4122, rfc4122, rfc4122, rfc4122], lists:map(fun uuid:variant/1, Uuids)), ?assertMatch([true, true, true, true], lists:map(fun uuid:is_valid/1, Uuids)), ?assertMatch([reserved_ncs, reserved_microsoft, reserved_future], lists:map(fun uuid:variant/1, [<<0:64, 0:1, 0:1, 0:1, 0:61>>, <<0:64, 1:1, 1:1, 0:1, 0:61>>, <<0:64, 1:1, 1:1, 1:1, 0:61>>])), ?assertMatch(false, uuid:is_valid(<<1:128>>)), ?assertMatch(true, uuid:is_valid(<<0:128>>)). stress_test_() -> {inparallel, {"uuid4 stress test.", {timeout, 10000, uuid4_stress()}}}. uuid4_stress() -> Count = 100000, Uuids = [uuid:uuid4() || _ <- lists:seq(1, Count)], Uniqs = lists:usort(Uuids), ?_assertEqual(Count, length(Uniqs)). do_randomized_and_timebased_uuids_change_enough_test() -> uuid_mask(fun uuid:uuid1/0, "^...XXXXX-....-1...-XXXX-............$"), uuid_mask(fun uuid:uuid4/0, "^XXXXXXXX-XXXX-4XXX-XXXX-XXXXXXXXXXXX$"). uuid_mask(F, Mask) -> ?assertEqual({match,[{0,36}]}, re:run(do_uuid_mask(F, 100), Mask)). do_uuid_mask(F, N) -> lists:foldl(fun mask/2, uuid:to_string(F()), [uuid:to_string(F()) || _ <- lists:seq(1,N)]). mask(X, Y) -> lists:map(fun eq_or_x/1, lists:zip(X, Y)). eq_or_x({X, X}) -> X; eq_or_x(_) -> $X. %% helper functions try_badarg(F, A) -> try apply(uuid, F, A) catch error:badarg -> ok end.