Skip to content

Commit

Permalink
Improve constructor performance (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
omus authored Oct 26, 2018
1 parent 8bf579f commit cc6aed3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/FixedPointDecimals.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,20 @@ struct FixedDecimal{T <: Integer, f} <: Real
if f >= 0 && (n < 0 || f <= n)
new{T, f}(i % T)
else
throw(ArgumentError(
"Requested number of decimal places $f exceeds the max allowed for the " *
"storage type $T: [0, $n]"
))
# Note: introducing a function barrier to improve performance
# https://github.com/JuliaMath/FixedPointDecimals.jl/pull/30
_throw_storage_error(f, T, n)
end
end
end

@noinline function _throw_storage_error(f, T, n)
throw(ArgumentError(
"Requested number of decimal places $f exceeds the max allowed for the " *
"storage type $T: [0, $n]"
))
end

const FD = FixedDecimal

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

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

max_exp10(::Type{BigInt}) = -1

"""
coefficient(::Type{FD{T, f}}) -> T
Expand Down
14 changes: 14 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,20 @@ end
x = FixedPointDecimals.max_exp10(T)
@test T(10)^x == widen(T(10))^x
end

@testset "custom integer types" begin
@eval begin
primitive type Int24 <: Integer 24 end
Base.typemax(::Type{Int24}) = 2^24
Base.widen(::Type{Int24}) = Int32
end

@test FixedPointDecimals.max_exp10(Int24) == 7

# Note: we're just pretending that this is unbounded
@eval primitive type IntUnbounded <: Integer 256 end
@test_throws MethodError FixedPointDecimals.max_exp10(IntUnbounded)
end
end

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

0 comments on commit cc6aed3

Please sign in to comment.