Skip to content

Commit cc6aed3

Browse files
authored
Improve constructor performance (#30)
1 parent 8bf579f commit cc6aed3

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

src/FixedPointDecimals.jl

+12-5
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,20 @@ struct FixedDecimal{T <: Integer, f} <: Real
9494
if f >= 0 && (n < 0 || f <= n)
9595
new{T, f}(i % T)
9696
else
97-
throw(ArgumentError(
98-
"Requested number of decimal places $f exceeds the max allowed for the " *
99-
"storage type $T: [0, $n]"
100-
))
97+
# Note: introducing a function barrier to improve performance
98+
# https://github.com/JuliaMath/FixedPointDecimals.jl/pull/30
99+
_throw_storage_error(f, T, n)
101100
end
102101
end
103102
end
104103

104+
@noinline function _throw_storage_error(f, T, n)
105+
throw(ArgumentError(
106+
"Requested number of decimal places $f exceeds the max allowed for the " *
107+
"storage type $T: [0, $n]"
108+
))
109+
end
110+
105111
const FD = FixedDecimal
106112

107113
(::Type{T})(x::Real) where {T <: FD} = convert(T, x)
@@ -460,7 +466,6 @@ The highest value of `x` which does not result in an overflow when evaluating `T
460466
types of `T` that do not overflow -1 will be returned.
461467
"""
462468
function max_exp10(::Type{T}) where {T <: Integer}
463-
applicable(typemax, T) || return -1
464469
W = widen(T)
465470
type_max = W(typemax(T))
466471

@@ -476,6 +481,8 @@ function max_exp10(::Type{T}) where {T <: Integer}
476481
exponent - 1
477482
end
478483

484+
max_exp10(::Type{BigInt}) = -1
485+
479486
"""
480487
coefficient(::Type{FD{T, f}}) -> T
481488

test/runtests.jl

+14
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,20 @@ end
109109
x = FixedPointDecimals.max_exp10(T)
110110
@test T(10)^x == widen(T(10))^x
111111
end
112+
113+
@testset "custom integer types" begin
114+
@eval begin
115+
primitive type Int24 <: Integer 24 end
116+
Base.typemax(::Type{Int24}) = 2^24
117+
Base.widen(::Type{Int24}) = Int32
118+
end
119+
120+
@test FixedPointDecimals.max_exp10(Int24) == 7
121+
122+
# Note: we're just pretending that this is unbounded
123+
@eval primitive type IntUnbounded <: Integer 256 end
124+
@test_throws MethodError FixedPointDecimals.max_exp10(IntUnbounded)
125+
end
112126
end
113127

114128
# ensure that the coefficient multiplied by the highest and lowest representable values of

0 commit comments

Comments
 (0)