Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Last active December 5, 2018 16:59
Show Gist options
  • Save peteristhegreat/828be89d8b3136fd073ce39929fd8359 to your computer and use it in GitHub Desktop.
Save peteristhegreat/828be89d8b3136fd073ce39929fd8359 to your computer and use it in GitHub Desktop.
Quick example of @BoundsCheck from the Julia REPL
@inline function a(perm, array)
@boundscheck begin
println("trying a boundscheck")
min, max = extrema(perm)
checkbounds(array, min)
checkbounds(array, max)
println("did a bounds check successfully")
end
println("done")
end
function b(do_check, perm, array)
if do_check
a(perm, array)
else
println("No bounds check")
@inbounds a(perm, array)
end
end
julia> b(true, [1,2,5], [5,5,5])
trying a boundscheck
ERROR: BoundsError: attempt to access 3-element Array{Int64,1} at index [5]
Stacktrace:
[1] throw_boundserror(::Array{Int64,1}, ::Tuple{Int64}) at ./abstractarray.jl:434
[2] checkbounds at ./abstractarray.jl:362 [inlined]
[3] a at ./REPL[39]:6 [inlined]
[4] b(::Bool, ::Array{Int64,1}, ::Array{Int64,1}) at ./REPL[47]:3
julia> b(false, [1,2,5], [5,5,5])
No bounds check
done
# https://docs.julialang.org/en/v1.0/base/base/#Base.@boundscheck
julia> @inline function g(A, i)
@boundscheck checkbounds(A, i)
return "accessing ($A)[$i]"
end;
julia> f1() = return g(1:2, -1);
julia> f2() = @inbounds return g(1:2, -1);
julia> f1()
ERROR: BoundsError: attempt to access 2-element UnitRange{Int64} at index [-1]
Stacktrace:
[1] throw_boundserror(::UnitRange{Int64}, ::Tuple{Int64}) at ./abstractarray.jl:455
[2] checkbounds at ./abstractarray.jl:420 [inlined]
[3] g at ./none:2 [inlined]
[4] f1() at ./none:1
[5] top-level scope
julia> f2()
"accessing (1:2)[-1]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment