Skip to content

Commit 28f1525

Browse files
author
Pietro Vertechi
committed
Document custom data layout
1 parent d326c9a commit 28f1525

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,35 @@ julia> map(t -> t.b ^ t.a, LazyRows(t))
164164
"x"
165165
"yy"
166166
```
167+
168+
## Advanced: structures with non-standard data layout
169+
170+
StructArrays support structures with non-standard data layout (where `getproperty` has been overloaded or where the constructors are non-standard). The user is required to provide an overloaded `staticscheme` for their type (to give the names and types of the properties of a given type) as well as a `createinstance` method. Here is an example of a type `MyType` that has as properties either its field `data` or properties of its field `rest` (which is a named tuple):
171+
172+
```julia
173+
using StructArrays
174+
struct MyType{NT<:NamedTuple}
175+
data::Float64
176+
rest::NT
177+
end
178+
179+
MyType(x; kwargs...) = MyType(x, values(kwargs))
180+
181+
Base.getproperty(b::MyType, s::Symbol) = s == :data ? getfield(b, 1) : getproperty(getfield(b, 2), s)
182+
183+
getnamestypes(::Type{NamedTuple{names, types}}) where {names, types} = (names, types)
184+
getnamestypes(::Type{MyType{NT}}) where NT = getnamestypes(NT)
185+
186+
function StructArrays.staticschema(::Type{T}) where {T<:MyType}
187+
names, types = getnamestypes(T)
188+
NamedTuple{(:data, names...), Base.tuple_type_cons(Float64, types)}
189+
end
190+
191+
function StructArrays.createinstance(::Type{T}, x, args...) where {T<:MyType}
192+
names, types = getnamestypes(T)
193+
MyType(x, NamedTuple{names, types}(args))
194+
end
195+
196+
s = [MyType(rand(), a=1, b=2) for i in 1:10]
197+
StructArray(s)
198+
```

0 commit comments

Comments
 (0)