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.
Widen type signature of bytes2hex
Browse files Browse the repository at this point in the history
Seelengrab committed Feb 20, 2021
1 parent 7040ffb commit 8e4f108
Showing 2 changed files with 16 additions and 10 deletions.
22 changes: 12 additions & 10 deletions base/strings/util.jl
Original file line number Diff line number Diff line change
@@ -666,12 +666,12 @@ end
throw(ArgumentError("byte is not an ASCII hexadecimal digit"))

"""
bytes2hex(a::AbstractArray{UInt8}) -> String
bytes2hex(io::IO, a::AbstractArray{UInt8})
bytes2hex(itr) -> String
bytes2hex(io::IO, itr)
Convert an array `a` of bytes to its hexadecimal string representation, either
returning a `String` via `bytes2hex(a)` or writing the string to an `io` stream
via `bytes2hex(io, a)`. The hexadecimal characters are all lowercase.
Convert an iterator `itr` of bytes to its hexadecimal string representation, either
returning a `String` via `bytes2hex(itr)` or writing the string to an `io` stream
via `bytes2hex(io, itr)`. The hexadecimal characters are all lowercase.
# Examples
```jldoctest
@@ -689,17 +689,19 @@ julia> bytes2hex(b)
"""
function bytes2hex end

function bytes2hex(a::Union{Tuple{Vararg{UInt8}}, AbstractArray{UInt8}})
b = Base.StringVector(2*length(a))
@inbounds for (i, x) in enumerate(a)
function bytes2hex(itr)
eltype(itr) === UInt8 || throw(ArgumentError("eltype of iterator not UInt8"))
b = Base.StringVector(2*length(itr))
@inbounds for (i, x) in enumerate(itr)
b[2i - 1] = hex_chars[1 + x >> 4]
b[2i ] = hex_chars[1 + x & 0xf]
end
return String(b)
end

function bytes2hex(io::IO, a::Union{Tuple{Vararg{UInt8}}, AbstractArray{UInt8}})
for x in a
function bytes2hex(io::IO, itr)
eltype(itr) != UInt8 && throw(ArgumentError("eltype of iterator not UInt8"))
for x in itr
print(io, Char(hex_chars[1 + x >> 4]), Char(hex_chars[1 + x & 0xf]))
end
end
4 changes: 4 additions & 0 deletions test/strings/util.jl
Original file line number Diff line number Diff line change
@@ -376,6 +376,10 @@ end
#non-hex characters
@test_throws ArgumentError hex2bytes(b"0123456789abcdefABCDEFGH")
end

@testset "Issue 39284" begin
@test "efcdabefcdab8967452301" == bytes2hex(Iterators.reverse(hex2bytes("0123456789abcdefABCDEF")))
end
end

# b"" should be immutable

0 comments on commit 8e4f108

Please sign in to comment.