It’s fairly simple to just redefine +
to be checked arithmetic… but you do need to rebuild Julia to avoid stack-overflows from checked_add
itself using +
:
Diff to Julia itself
shell> git diff
diff --git a/base/checked.jl b/base/checked.jl
index ad92a44e1e..6c925c2d83 100644
--- a/base/checked.jl
+++ b/base/checked.jl
@@ -135,7 +135,7 @@ add_with_overflow(x::Bool, y::Bool) = (x+y, false)
if BrokenSignedInt != Union{}
function add_with_overflow(x::T, y::T) where T<:BrokenSignedInt
- r = x + y
+ r = add_int(x, y)
# x and y have the same sign, and the result has a different sign
f = (x<0) == (y<0) != (r<0)
r, f
@@ -145,7 +145,7 @@ if BrokenUnsignedInt != Union{}
function add_with_overflow(x::T, y::T) where T<:BrokenUnsignedInt
# x + y > typemax(T)
# Note: ~y == -y-1
- x + y, x > ~y
+ add_int(x, y), x > ~y
end
end
diff --git a/base/tuple.jl b/base/tuple.jl
index b45e1efc91..5356bb693a 100644
--- a/base/tuple.jl
+++ b/base/tuple.jl
@@ -85,8 +85,8 @@ end
# this allows partial evaluation of bounded sequences of next() calls on tuples,
# while reducing to plain next() for arbitrary iterables.
-indexed_iterate(t::Tuple, i::Int, state=1) = (@inline; (getfield(t, i), i+1))
-indexed_iterate(a::Array, i::Int, state=1) = (@inline; (a[i], i+1))
+indexed_iterate(t::Tuple, i::Int, state=1) = (@inline; (getfield(t, i), add_int(i,1)))
+indexed_iterate(a::Array, i::Int, state=1) = (@inline; (a[i], add_int(i,1)))
function indexed_iterate(I, i)
x = iterate(I)
x === nothing && throw(BoundsError(I, i))
At that point, you can just redefine +
:
julia> Base.:+(x::T, y::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} = Base.checked_add(x, y)
but things break pretty quickly:
julia> ┌ Error: Error in the keymap
│ exception =
│ OverflowError: 15057391676429522544 + 8207575013956623489 overflowed for type UInt64
│ Stacktrace:
│ [1] throw_overflowerr_binaryop(op::Symbol, x::UInt64, y::UInt64)
│ @ Base.Checked ./checked.jl:154
│ [2] checked_add
│ @ ./checked.jl:166 [inlined]
│ [3] +
│ @ ./REPL[1]:1 [inlined]
│ [4] hash
│ @ ./hashing.jl:107 [inlined]