Skip to content

Commit 8563a51

Browse files
author
Pietro Vertechi
authored
implemented similar (JuliaArrays#27)
1 parent 175d0b5 commit 8563a51

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/structarray.jl

+13-3
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ struct StructArray{T, N, C<:NamedTuple} <: AbstractArray{T, N}
88

99
function StructArray{T, N, C}(c) where {T, N, C<:NamedTuple}
1010
length(c) > 0 || error("must have at least one column")
11-
n = size(c[1])
12-
length(n) == N || error("wrong number of dimensions")
11+
ax = axes(c[1])
12+
length(ax) == N || error("wrong number of dimensions")
1313
for i = 2:length(c)
14-
size(c[i]) == n || error("all columns must have same size")
14+
axes(c[i]) == ax || error("all columns must have same size")
1515
end
1616
new{T, N, C}(c)
1717
end
@@ -60,6 +60,15 @@ StructArray(s::StructArray) = copy(s)
6060

6161
Base.convert(::Type{StructArray}, v::AbstractArray) = StructArray(v)
6262

63+
function Base.similar(::Type{StructArray{T, N, C}}, sz::Dims) where {T, N, C}
64+
cols = map_params(typ -> similar(typ, sz), C)
65+
StructArray{T}(cols)
66+
end
67+
68+
Base.similar(s::S, sz::Tuple) where {S<:StructArray} = similar(S, Base.to_shape(sz))
69+
Base.similar(s::S, sz::Base.DimOrInd...) where {S<:StructArray} = similar(S, Base.to_shape(sz))
70+
Base.similar(s::S) where {S<:StructArray} = similar(S, Base.to_shape(axes(s)))
71+
6372
columns(s::StructArray) = getfield(s, :columns)
6473
columns(v::AbstractVector) = v
6574
ncols(v::AbstractVector) = 1
@@ -72,6 +81,7 @@ Base.getproperty(s::StructArray, key::Int) = getfield(columns(s), key)
7281
Base.propertynames(s::StructArray) = fieldnames(typeof(columns(s)))
7382

7483
Base.size(s::StructArray) = size(columns(s)[1])
84+
Base.axes(s::StructArray) = axes(columns(s)[1])
7585

7686
@generated function Base.getindex(x::StructArray{T, N, NamedTuple{names, types}}, I::Int...) where {T, N, names, types}
7787
args = [:(getfield(cols, $i)[I...]) for i in 1:length(names)]

test/runtests.jl

+14
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,20 @@ end
2020
@test StructArrays.colnames(t.a) == (1,)
2121
end
2222

23+
@testset "similar" begin
24+
t = StructArray(a = rand(10), b = rand(Bool, 10))
25+
s = similar(t)
26+
@test eltype(s) == NamedTuple{(:a, :b), Tuple{Float64, Bool}}
27+
@test size(s) == (10,)
28+
t = StructArray(a = rand(10, 2), b = rand(Bool, 10, 2))
29+
s = similar(t, 3, 5)
30+
@test eltype(s) == NamedTuple{(:a, :b), Tuple{Float64, Bool}}
31+
@test size(s) == (3, 5)
32+
s = similar(t, (3, 5))
33+
@test eltype(s) == NamedTuple{(:a, :b), Tuple{Float64, Bool}}
34+
@test size(s) == (3, 5)
35+
end
36+
2337
@testset "empty" begin
2438
s = StructVector(a = [1, 2, 3], b = ["a", "b", "c"])
2539
empty!(s)

0 commit comments

Comments
 (0)