Skip to content

bytes2hex(::Union{NTuple{Any, UInt8}, AbstractArray{UInt8}}) is needlessly restrictive #39284

Closed
@Seelengrab

Description

@Seelengrab

I've recently had the problem of using bytes2hex on the reverse of a large vector that mustn't be modified (and copying it would be unnecessary, as bytes2hex already allocates). The arguments for bytes2hex are restricted by Union{NTuple{Any, UInt8}, AbstractArray{UInt8}} though, so using Iterators.reverse to save the copying wasn't an option. bytes2hex doesn't require its argument to be an array though - being iterable, having a length and having an eltype of UInt8 is enough.

For my specific problem, adding the following method was enough to fix it:

function bytes2hex(a::Base.Iterators.Reverse{<:AbstractVector{UInt8}})
    b = Base.StringVector(2*length(a))
    @inbounds for (i, x) in enumerate(a)
        b[2i - 1] = hex_chars[1 + x >> 4]
        b[2i    ] = hex_chars[1 + x & 0xf]
    end
    return String(b)
end

This won't work for general iterables of course, which is why I opened this issue instead of a PR widening the type signature. I'm mostly looking for ideas on how to best widen the signature and would submit a PR implementing it once we've decided on a design.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions