Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

uuid5 #28761

Merged
merged 6 commits into from
Sep 26, 2018
Merged

uuid5 #28761

Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions stdlib/UUIDs/docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ DocTestSetup = :(using UUIDs, Random)
```@docs
UUIDs.uuid1
UUIDs.uuid4
UUIDs.uuid5
UUIDs.uuid_version
```

Expand Down
34 changes: 33 additions & 1 deletion stdlib/UUIDs/src/UUIDs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ module UUIDs

using Random

export UUID, uuid1, uuid4, uuid_version
import SHA

export UUID, uuid1, uuid4, uuid5, uuid_version

import Base: UUID

Expand Down Expand Up @@ -81,4 +83,34 @@ function uuid4(rng::AbstractRNG=Random.GLOBAL_RNG)
UUID(u)
end

"""
uuid5(ns::UUID, name::String) -> UUID

Generates a version 5 (namespace and domain-based) universally unique identifier (UUID),
as specified by RFC 4122.

# Examples
```jldoctest
julia> rng = MersenneTwister(1234);

julia> u4 = uuid4(rng)
UUID("196f2941-2d58-45ba-9f13-43a2532b2fa8")

julia> u5 = uuid5(u4, "julia")
UUID("6f461186-52d8-5fc1-993a-77a729165b65")
```
"""
function uuid5(ns::UUID, name::String)
hash_result = SHA.sha1(string(ns,name))
# set version number to 5
hash_result[7] = (hash_result[7] & 0x0F) | (0x50)
hash_result[9] = (hash_result[9] & 0x3F) | (0x80)
v = zero(UInt128)
#use only the first 16 bytes of the SHA1 hash
for idx in Base.OneTo(16)
matbesancon marked this conversation as resolved.
Show resolved Hide resolved
v = (v << 0x08) | hash_result[idx]
end
return UUID(v)
end

end
4 changes: 4 additions & 0 deletions stdlib/UUIDs/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ using Test, UUIDs, Random

u1 = uuid1()
u4 = uuid4()
u5 = uuid5(u1, "julia")
@test uuid_version(u1) == 1
@test uuid_version(u4) == 4
@test uuid_version(u5) == 5
@test u1 == UUID(string(u1)) == UUID(GenericString(string(u1)))
@test u4 == UUID(string(u4)) == UUID(GenericString(string(u4)))
@test u5 == UUID(string(u5)) == UUID(GenericString(string(u5)))
@test u1 == UUID(UInt128(u1))
@test u4 == UUID(UInt128(u4))
@test u5 == UUID(UInt128(u5))
@test uuid4(MersenneTwister(0)) == uuid4(MersenneTwister(0))
@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-446655440000")
@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-44665544000098")
Expand Down