Skip to content

Commit 8e524c7

Browse files
authored
Add a similar method for Type{<:CodeUnits} (#57826)
Currently, `similar(::CodeUnits)` works as expected by going through the generic `AbstractArray` method. However, the fallback method hit by `similar(::Type{<:CodeUnits}, dims)` does not work, as it assumes the existence of a constructor that accepts an `UndefInitializer`. This can be made to work by defining a corresponding `similar` method that returns an `Array`. One could make a case that this is a bugfix since it was arguably a bug that this method didn't work given that `CodeUnits` is an `AbstractArray` subtype and the other `similar` methods work. If anybody buys that argument, it could be nice to backport this; it came up in some internal code that uses Arrow.jl and JSON3.jl together.
1 parent d49773c commit 8e524c7

File tree

2 files changed

+3
-0
lines changed

2 files changed

+3
-0
lines changed

base/strings/basic.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,8 @@ write(io::IO, s::CodeUnits) = write(io, s.s)
805805
cconvert(::Type{Ptr{T}}, s::CodeUnits{T}) where {T} = cconvert(Ptr{T}, s.s)
806806
cconvert(::Type{Ptr{Int8}}, s::CodeUnits{UInt8}) = cconvert(Ptr{Int8}, s.s)
807807

808+
similar(::Type{<:CodeUnits{T}}, dims::Dims) where {T} = similar(Array{T}, dims)
809+
808810
"""
809811
codeunits(s::AbstractString)
810812

test/strings/basic.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1096,6 +1096,7 @@ let s = "∀x∃y", u = codeunits(s)
10961096
@test_throws Base.CanonicalIndexError (u[1] = 0x00)
10971097
@test collect(u) == b"∀x∃y"
10981098
@test Base.elsize(u) == Base.elsize(typeof(u)) == 1
1099+
@test similar(typeof(u), 3) isa Vector{UInt8}
10991100
end
11001101

11011102
@testset "issue #24388" begin

0 commit comments

Comments
 (0)