Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/UnPack.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ This function is invoked to unpack one field/entry of some DataType

The `sym` is the symbol of the assigned variable.

Three definitions are included in the package to unpack a composite type
or a dictionary with Symbol or string keys:
Four definitions are included in the package to unpack a composite type,
a dictionary with `Symbol` or string keys, or a `RegexMatch`:
```
@inline unpack(x, ::Val{f}) where {f} = getproperty(x, f)
@inline unpack(x::AbstractDict{Symbol}, ::Val{k}) where {k} = x[k]
@inline unpack(x::AbstractDict{S}, ::Val{k}) where {S<:AbstractString,k} = x[string(k)]
@inline unpack(x::RegexMatch, ::Val{k}) where {k} = x[k]
```

More methods can be added to allow for specialized unpacking of other datatypes.
Expand All @@ -34,6 +35,7 @@ function unpack end
@inline unpack(x, ::Val{f}) where {f} = getproperty(x, f)
@inline unpack(x::AbstractDict{Symbol}, ::Val{k}) where {k} = x[k]
@inline unpack(x::AbstractDict{<:AbstractString}, ::Val{k}) where {k} = x[string(k)]
@inline unpack(x::RegexMatch, ::Val{k}) where {k} = x[k]

"""
This function is invoked to pack one entity into some DataType and has
Expand Down Expand Up @@ -86,6 +88,14 @@ a == 4 #true
c == "Hi" #true
```

Example with regex match:
```julia
m = match(r"(?<a>.) -> (?<b>.)", "2 -> 1")
@unpack a, b = m
a == "2" #true
b == "1" #true
```

Note that its functionality can be extended by adding methods to the
`UnPack.unpack` function.
"""
Expand Down
8 changes: 8 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ using Test
@test c == "Hi!" #true
end

@testset "RegexMatch" begin
# Example with regex match:
m = match(r"(?<a>.) -> (?<b>.)", "2 -> 1")
@unpack a, b = m
@test a == "2" #true
@test b == "1" #true
end

# having struct-defs inside a testset seems to be problematic in some julia version
mutable struct PropertyExample
a
Expand Down