From ce6998d8de2b7a6de5611c234713619a9914cc13 Mon Sep 17 00:00:00 2001 From: Alex Arslan Date: Tue, 18 Mar 2025 16:19:47 -0700 Subject: [PATCH] Add a `similar` method for `Type{<:CodeUnits}` 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 method that returns an `Array`. --- base/strings/basic.jl | 2 ++ test/strings/basic.jl | 1 + 2 files changed, 3 insertions(+) diff --git a/base/strings/basic.jl b/base/strings/basic.jl index 3748424a18aa7..03f5227d54b34 100644 --- a/base/strings/basic.jl +++ b/base/strings/basic.jl @@ -805,6 +805,8 @@ write(io::IO, s::CodeUnits) = write(io, s.s) cconvert(::Type{Ptr{T}}, s::CodeUnits{T}) where {T} = cconvert(Ptr{T}, s.s) cconvert(::Type{Ptr{Int8}}, s::CodeUnits{UInt8}) = cconvert(Ptr{Int8}, s.s) +similar(::Type{<:CodeUnits{T}}, dims::Dims) where {T} = Array{T}(undef, dims) + """ codeunits(s::AbstractString) diff --git a/test/strings/basic.jl b/test/strings/basic.jl index c3e0bcc501070..f36f45e9a2ce3 100644 --- a/test/strings/basic.jl +++ b/test/strings/basic.jl @@ -1078,6 +1078,7 @@ let s = "∀x∃y", u = codeunits(s) @test_throws Base.CanonicalIndexError (u[1] = 0x00) @test collect(u) == b"∀x∃y" @test Base.elsize(u) == Base.elsize(typeof(u)) == 1 + @test similar(typeof(u), 3) isa Vector{UInt8} end @testset "issue #24388" begin