Skip to content

Commit 203d1f2

Browse files
committed
Clean up promotion with union type
1 parent 36b6c80 commit 203d1f2

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

src/utils.jl

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,22 +49,21 @@ end
4949
# or even <:AbstractFloat, as it could conflict with other
5050
# abstract number packages which may try to do the same thing.
5151
# (which would lead to ambiguities)
52-
for (type, _, _) in ABSTRACT_QUANTITY_TYPES, numeric_type in (
52+
const BASE_NUMERIC_TYPES = Union{
5353
Bool, Int8, UInt8, Int16, UInt16, Int32, UInt32,
5454
Int64, UInt64, Int128, UInt128, Float16, Float32,
5555
Float64, BigFloat, BigInt, ComplexF16, ComplexF32,
5656
ComplexF64, Complex{BigFloat}, Rational{Int8}, Rational{UInt8},
5757
Rational{Int16}, Rational{UInt16}, Rational{Int32}, Rational{UInt32},
5858
Rational{Int64}, Rational{UInt64}, Rational{Int128}, Rational{UInt128},
5959
Rational{BigInt},
60-
)
61-
@eval begin
62-
function Base.promote_rule(::Type{Q}, ::Type{$numeric_type}) where {T,D,Q<:$type{T,D}}
63-
return with_type_parameters(Q, promote_type(T,$numeric_type), D)
64-
end
65-
function Base.convert(::Type{Q}, x::$numeric_type) where {T,D,Q<:$type{T,D}}
66-
return new_quantity(Q, convert(T, x), D())
67-
end
60+
}
61+
for (type, _, _) in ABSTRACT_QUANTITY_TYPES
62+
@eval function Base.promote_rule(::Type{Q}, ::Type{T2}) where {T,D,Q<:$type{T,D},T2<:BASE_NUMERIC_TYPES}
63+
return with_type_parameters(Q, promote_type(T, T2), D)
64+
end
65+
@eval function Base.convert(::Type{Q}, x::BASE_NUMERIC_TYPES) where {T,D,Q<:$type{T,D}}
66+
return new_quantity(Q, convert(T, x), D())
6867
end
6968
end
7069
function Base.promote_rule(::Type{<:AbstractQuantity}, ::Type{<:Number})

test/unittests.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,17 @@ end
461461
x = [0.5, q]
462462
@test x isa Vector{typeof(q)}
463463

464+
# Promotion with custom numeric type:
465+
@eval struct MyNumber <: Real
466+
x::Float64
467+
end
468+
a = 0.5u"km/s"
469+
b = MyNumber(0.5)
470+
ar = [a, b]
471+
@test ar isa Vector{Number}
472+
@test a === ar[1]
473+
@test b === ar[2]
474+
464475
# Explicit conversion so coverage can see it:
465476
D = DEFAULT_DIM_TYPE
466477
@test promote_type(Quantity{Float32,D}, Float64) == Quantity{Float64,D}

0 commit comments

Comments
 (0)