Adapt.WrappedArray
— TypeWrappedArray{T,N,Src,Dst}
Union-type that encodes all array wrappers known by Adapt.jl. Typevars T
and N
encode the type and dimensionality of the resulting container.
Two additional typevars are used to encode the parent array type: Src
when the wrapper uses the parent array as a source, but changes its properties (e.g. SubArray{T,1,Array{T,2}
changes N
), and Dst
when those properties are copied and thus are identical to the destination wrapper's properties (e.g. Transpose{T,Array{T,N}}
has the same dimensionality as the inner array). When creating an alias for this type, e.g. WrappedSomeArray{T,N} = WrappedArray{T,N,...}
the Dst
typevar should typically be set to SomeArray{T,N}
while Src
should be more lenient, e.g., SomeArray
.
Only use this type for dispatch purposes. To convert instances of an array wrapper, use adapt
.
Adapt.adapt
— Methodadapt(to, x)
Adapt a value x
according to to
. If no specific adaptions have been registered for to
, this call will be a no-op.
To alter the behavior, implement methods of adapt_structure
and adapt_storage
to respectively define how to adapt structures, and the leaves of those structures.
For example, defining an adaptor for an environment where we can't have integers, and adding a method to adapt_storage
to appropriately convert those to floating-point numbers:
julia> struct IntegerLessAdaptor end
julia> Adapt.adapt_storage(::IntegerLessAdaptor, x::Int64) = Float64(x)
julia> adapt(IntegerLessAdaptor(), 42)
42.0
This will automatically work on known types too:
julia> adapt(IntegerLessAdaptor(), tuple(1,2,3))
(1.0, 2.0, 3.0)
If we want this to work with custom structures, we need to extend adapt_structure
:
julia> struct MyStructure
x
end
julia> Adapt.adapt_structure(to, obj::MyStructure) = MyStructure(adapt(to, obj.x))
julia> adapt(IntegerLessAdaptor(), MyStructure(42))
MyStructure(42.0)
Adapt.adapt
— Methodadapt(to)
Create a function that adapts its argument according to to
. If no specific adaptions have been registered for to
, the returned function will be equivalent to identity
.
Adapt.parent_type
— Method parent_type(W::Type{<:WrappedArray})
Return the parent type of a wrapped array type. This is the type of the array that is wrapped by the wrapper, e.g. parent_type(SubArray{Int, 1, Matrix{Int}}) == Matrix{Int}
.
Adapt.unwrap_type
— Method unwrap_type(W::Type{<:WrappedArray})
Fully unwrap a wrapped array type, i.e., returns the parent_type
until the result is no longer a wrapped array type. This is useful for accessing properties of the innermost array type.
Adapt.@adapt_structure
— MacroAdapt.@adapt_structure T
Define a method adapt_structure(to, obj::T)
which calls adapt_structure
on each field of obj
and constructs a new instance of T
using the default constuctor T(...)
.