Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
Heptazhou committed Apr 6, 2024
1 parent b9ee948 commit 9dd14bd
Show file tree
Hide file tree
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
Expand Up @@ -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
Expand Down Expand Up @@ -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, "-" => ""; count)
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

"""
Expand Down
4 changes: 3 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit 9dd14bd

Please sign in to comment.