JeffreySarnoff / SaferIntegers.jl

These integer types use checked arithmetic, otherwise they are as system types.
MIT License
59 stars 9 forks source link

Promotion fails when comparing safe and unsafe ints #42

Closed nhz2 closed 8 months ago

nhz2 commented 8 months ago
julia> UInt(1) > -1
true

julia> SafeUInt(1) > -1
ERROR: InexactError: check_top_bit(UInt64, -1)
Stacktrace:
  [1] throw_inexacterror(f::Symbol, ::Type{UInt64}, val::Int64)
    @ Core ./boot.jl:634
  [2] check_top_bit
    @ Core ./boot.jl:648 [inlined]
  [3] toUInt64
    @ Core ./boot.jl:759 [inlined]
  [4] UInt64
    @ Core ./boot.jl:789 [inlined]
  [5] SafeUInt64
    @ SaferIntegers ~/.julia/packages/SaferIntegers/h4nCJ/src/construct.jl:75 [inlined]
  [6] convert
    @ Base ./number.jl:7 [inlined]
  [7] _promote
    @ Base ./promotion.jl:370 [inlined]
  [8] promote
    @ Base ./promotion.jl:393 [inlined]
  [9] >(x::SafeUInt64, y::Int64)
    @ SaferIntegers ~/.julia/packages/SaferIntegers/h4nCJ/src/binary_ops.jl:42
 [10] top-level scope
    @ REPL[33]:1
JeffreySarnoff commented 8 months ago

This comes from

julia> promote(UInt(1), Int(-1))
ERROR: InexactError: check_top_bit(UInt64, -1)

I see in your example that Julia sidesteps this promotion in comparisons. It is unclear to me that this is an entirely safe practice. What is your opinion?

nhz2 commented 8 months ago

Yes, there may need to be a special case for comparisons, but I haven't thought about how to do that safely. Are all of the comparisons using base Integer types already overflow safe? If so maybe those base operations can be used as is.

JeffreySarnoff commented 8 months ago

I certainly hope so :). That was an initial design specification.