Skip to content

Commit 6d49028

Browse files
authored
Optional: conversion from other AbstractVector (#25)
1 parent a82f2a8 commit 6d49028

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/ParseUnparse.jl

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,30 @@ module ParseUnparse
4444
function Base.iterate(::Optional, ::Any)
4545
nothing
4646
end
47+
function convert_from_other_vector_eltype(::Type{Optional{T}}, ::Type) where {T}
48+
T
49+
end
50+
function convert_from_other_vector_eltype(::Type{Optional}, ::Type{T}) where {T}
51+
T
52+
end
53+
function convert_from_other_vector(::Type{O}, vec::AbstractVector) where {O <: Optional}
54+
if 1 < length(vec)
55+
throw(ArgumentError("got vector with more than one element, too long"))
56+
end
57+
T = convert_from_other_vector_eltype(O, eltype(vec))
58+
Op = Optional{T}
59+
if isempty(vec)
60+
Op()
61+
else
62+
Op(only(vec))
63+
end
64+
end
65+
function Base.convert(::Type{Optional{T}}, vec::AbstractVector) where {T}
66+
convert_from_other_vector(Optional{T}, vec)
67+
end
68+
function Base.convert(::Type{Optional}, vec::AbstractVector)
69+
convert_from_other_vector(Optional, vec)
70+
end
4771
end
4872
"""
4973
ContextFreeGrammarUtil::Module

test/runtests_optionals.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,12 @@ using Test
1919
@test [3] == collect(Float32, Optional(3))
2020
@test_throws BoundsError Optional(3.0)[2]
2121
@test_throws BoundsError Optional{Int}()[1]
22+
@test (@inferred convert(Optional, Float32[])) isa Optional{Float32}
23+
@test isempty(convert(Optional, Float32[]))
24+
@test Optional(3) === convert(Optional, [3])
25+
@test (@inferred convert(Optional{Float64}, Float32[])) isa Optional{Float64}
26+
@test isempty(convert(Optional{Float64}, Float32[]))
27+
@test Optional(3.0) === convert(Optional{Float64}, [3])
28+
@test_throws ArgumentError convert(Optional, [3, 7])
29+
@test_throws ArgumentError convert(Optional{Float64}, [3, 7])
2230
end

0 commit comments

Comments
 (0)