Skip to content

Commit 88cd163

Browse files
committed
Support promotion among UFixed types
1 parent 0131751 commit 88cd163

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

src/ufixed.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,15 @@ promote_rule{T<:UFixed, R<:Rational}(::Type{T}, ::Type{R}) = R
151151
Tp = eps(convert(Float32, typemax(Ti))) > eps(T) ? Float64 : Float32
152152
:( $Tp )
153153
end
154+
@generated function promote_rule{T1,T2,f1,f2}(::Type{UFixed{T1,f1}}, ::Type{UFixed{T2,f2}})
155+
f = max(f1, f2) # ensure we have enough precision
156+
T = promote_type(T1, T2)
157+
# make sure we have enough integer bits
158+
i1, i2 = 8*sizeof(T1)-f1, 8*sizeof(T2)-f2 # number of integer bits for each
159+
i = 8*sizeof(T)-f
160+
while i < max(i1, i2)
161+
T = widen1(T)
162+
i = 8*sizeof(T)-f
163+
end
164+
:(UFixed{$T,$f})
165+
end

test/ufixed.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,14 @@ end
169169
r = 1uf8:1uf8:48uf8
170170
@test length(r) == 48
171171

172+
# Promotion within UFixed
173+
@test @inferred(promote(UFixed8(0.2), UFixed8(0.8))) ===
174+
(UFixed8(0.2), UFixed8(0.8))
175+
@test @inferred(promote(UFixed{UInt16,3}(0.2), UFixed{UInt8,3}(0.86))) ===
176+
(UFixed{UInt16,3}(0.2), UFixed{UInt16,3}(0.86))
177+
@test @inferred(promote(UFixed{UInt8,7}(0.197), UFixed{UInt8,4}(0.8))) ===
178+
(UFixed{UInt16,7}(0.197), UFixed{UInt16,7}(0.8))
179+
172180
# Show
173181
x = 0xaauf8
174182
iob = IOBuffer()

0 commit comments

Comments
 (0)