Skip to content

Commit 77b494d

Browse files
briochemcmauro3
authored andcommitted
Update README.md (#2)
1 parent 79aa697 commit 77b494d

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

README.md

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ determined by the functions `UnPack.unpack` and `UnPack.pack!`.
5555
The `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

6062
Note that `unpack` (and `pack!`) works with `Base.getproperty`. By
6163
default 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
6466
Three method definitions are included in the package to unpack a
6567
composite type/module/NamedTuple, or a dictionary with Symbol or
6668
string 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:
7376
The `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

7883
Three definitions are included in the package to pack into a mutable composite
7984
type 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

8692
More 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

Comments
 (0)