diff --git a/README.md b/README.md index 0b15241..f40483a 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,17 @@ julia> malloc(Int, 4, 4) julia> free(ans) ``` +It is also possible to construct a `PtrArray` using the usual array constructor interface with `undef`: + +```julia-repl +julia> PtrArray{Float64}(undef, 4, 4) +4×4 PtrArray{Float64, 2}: + 7.01389e-316 7.2e-322 2.0e-323 0.0 + 0.0 1.294e-321 2.47e-322 0.0 + 4.2e-322 0.0 2.87e-322 6.37223e-316 + 5.53e-322 0.0 4.05e-322 4.24399e-314 +``` + Benchmarks: ```julia diff --git a/src/PtrArrays.jl b/src/PtrArrays.jl index 4a3003f..ae780f5 100644 --- a/src/PtrArrays.jl +++ b/src/PtrArrays.jl @@ -65,6 +65,19 @@ function malloc(::Type{T}, dims::Int...) where T PtrArray(Ptr{T}(ptr), dims..., check_dims=false) end +function PtrArray{T, N}(::UndefInitializer, dims::Vararg{Int, N}) where {T, N} + malloc(T, dims...) +end +function PtrArray{T, N}(::UndefInitializer, dims::Tuple{Vararg{Int, N}}) where {T, N} + malloc(T, dims...) +end +function PtrArray{T}(::UndefInitializer, dims::Vararg{Int}) where {T} + malloc(T, dims...) +end +function PtrArray{T}(::UndefInitializer, dims::Tuple{Vararg{Int}}) where {T} + malloc(T, dims...) +end + """ free(p::PtrArray) diff --git a/test/runtests.jl b/test/runtests.jl index 65ea77a..40a8325 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -61,6 +61,15 @@ end free(s) end +@testset "undef constructors" begin + @test (@inferred PtrArray{Float32}(undef, 3, 3)) isa PtrArray{Float32, 2} + @test (@inferred PtrArray{Float32}(undef, (3, 3))) isa PtrArray{Float32, 2} + @test (@inferred PtrArray{Float32, 2}(undef, 3, 3)) isa PtrArray{Float32, 2} + @test (@inferred PtrArray{Float32, 2}(undef, (3, 3))) isa PtrArray{Float32, 2} + @test_throws MethodError PtrArray{Float32, 2}(undef, 3) + @test_throws MethodError PtrArray{Float32, 2}(undef, (3,)) +end + function f(x, y) z = malloc(Int, x) z .= y