@@ -55,7 +55,9 @@ determined by the functions `UnPack.unpack` and `UnPack.pack!`.
5555The ` UnPack.unpack ` function is invoked to unpack one entity of some
5656` DataType ` and has signature:
5757
58- ` unpack(dt::Any, ::Val{property}) -> value of property `
58+ ``` julia
59+ unpack (dt:: Any , :: Val{property} ) -> value of property
60+ ```
5961
6062Note that ` unpack ` (and ` pack! ` ) works with ` Base.getproperty ` . By
6163default this means that all the fields of a type are unpacked but if
@@ -64,7 +66,8 @@ default this means that all the fields of a type are unpacked but if
6466Three method definitions are included in the package to unpack a
6567composite type/module/NamedTuple, or a dictionary with Symbol or
6668string keys:
67- ```
69+
70+ ``` julia
6871@inline unpack {f} (x, :: Val{f} ) = getproperty (x, f)
6972@inline unpack {k} (x:: Associative{Symbol} , :: Val{k} ) = x[k]
7073@inline unpack {S<:AbstractString,k} (x:: Associative{S} , :: Val{k} ) = x[string (k)]
@@ -73,15 +76,35 @@ string keys:
7376The ` UnPack.pack! ` function is invoked to pack one entity into some
7477` DataType ` and has signature:
7578
76- ` pack!(dt::Any, ::Val{field}, value) -> value `
79+ ``` julia
80+ pack! (dt:: Any , :: Val{field} , value) -> value
81+ ```
7782
7883Three definitions are included in the package to pack into a mutable composite
7984type or into a dictionary with Symbol or string keys:
80- ```
85+
86+ ``` julia
8187@inline pack! {f} (x, :: Val{f} , val) = setproperty! (x, f, val)
8288@inline pack! {k} (x:: Associative{Symbol} , :: Val{k} , val) = x[k]= val
8389@inline pack! {S<:AbstractString,k} (x:: Associative{S} , :: Val{k} , val) = x[string (k)]= val
8490```
8591
8692More methods can be added to ` unpack ` and ` pack! ` to allow for
87- specialized packing of datatypes.
93+ specialized unpacking/packing of datatypes. Here is a MWE of customizing
94+ ` unpack ` , so that it multiplies the values by 2:
95+
96+ ``` julia
97+ using UnPack
98+ struct Foo
99+ a
100+ b
101+ end
102+ p = Foo (1 , 2 )
103+ @unpack a, b = p
104+ a, b # gives (1, 2)
105+
106+ # Now we specialize unpack for our custom type, `Foo`
107+ @inline UnPack. unpack (x:: Foo , :: Val{f} ) where {f} = 2 * getproperty (x, f)
108+ @unpack a, b = p
109+ a, b # now gives (2, 4)
110+ ```
0 commit comments