Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update
Browse files Browse the repository at this point in the history
Heptazhou committed Apr 6, 2024

Verified

This commit was signed with the committer’s verified signature.
Heptazhou Heptazhou
1 parent b9ee948 commit a6246cb
Showing 2 changed files with 24 additions and 10 deletions.
30 changes: 21 additions & 9 deletions src/UUID4.jl
Original file line number Diff line number Diff line change
@@ -78,18 +78,18 @@ function uuid_formats()::Vector{Int}
end

"""
uuid_parse(str::AbstractString; fmt::Int = length(str)) -> Tuple{Int, UUID}
uuid_parse(str::AbstractString; fmt::Int = ncodeunits(str)) -> Tuple{Int, UUID}
"""
function uuid_parse end
function uuid_parse(id::UUID)::Tuple{Int, UUID}
(length("$id"), id) # (36, id)
(36, id)
end
function uuid_parse(str::AbstractString; fmt::Int = 0)::Tuple{Int, UUID}
len = length(str)
len = ncodeunits(str)
(id = uuid_tryparse(str)) |> isnothing &&
argumenterror("Invalid id `$str` with length = $len")
argumenterror("Invalid id `$str` with ncodeunits = $len")
if 0 < fmt len
argumenterror("Invalid id `$str` with length = $len (should be $fmt)")
argumenterror("Invalid id `$str` with ncodeunits = $len (should be $fmt)")
elseif fmt < 0
argumenterror("Invalid format `$fmt` (should be positive)")
end
@@ -159,15 +159,27 @@ end
"""
uuid_tryparse(s::AbstractString) -> Maybe{Union{UInt128, UUID}}
"""
function uuid_tryparse end
let
#! format: noindent
function dropdash(s::AbstractString; step::Int, count::Int)
for i 1:count
@inbounds UInt8('-') codeunit(s, (1 + step)i) && return ""
end
replace(s, "-" => "")
end

function uuid_tryparse(str::AbstractString)::Maybe{Union{UInt128, UUID}}
len = ncodeunits(str)
len 24 ? uuid_tryparse(replace(str, "-" => "")) :
len 29 ? uuid_tryparse(replace(str, "-" => "")) :
len 39 ? uuid_tryparse(replace(str, "-" => "")) :
len 24 ? uuid_tryparse(dropdash(str, step = 7, count = len - 22)) :
len 29 ? uuid_tryparse(dropdash(str, step = 5, count = len - 25)) :
len 39 ? uuid_tryparse(dropdash(str, step = 4, count = len - 32)) :
len 22 ? Base.tryparse(UInt128, str, base = 62) :
len 25 ? Base.tryparse(UInt128, str, base = 36) :
len 32 ? Base.tryparse(UInt128, str, base = 16) :
len 36 ? Base.tryparse(UUID, str) : nothing
len 36 ? Base.tryparse(UUID, str) : (nothing)
end
global uuid_tryparse
end

"""
4 changes: 3 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
@@ -42,7 +42,9 @@ str = "22b4a8a1-e548-4eeb-9270-60426d66a48e"
@test_throws ArgumentError UUID("22b4a8a1-e548-4eeb-9270a60426d66a48e")
@test UUID(uppercase(str)) == UUID(str)
for r rand(UInt128, 10^3)
@test UUID(r) == UUID(string(UUID(r)))
s = string(UUID(r))
@test UUID(r) == UUID(s)
@test ncodeunits(s) === length(s) === 36
end

fmt = [22, 24, 25, 29, 32, 36, 39]

0 comments on commit a6246cb

Please sign in to comment.