From 2a26531f0688cb8a5995542ac6bdb63353d2adec Mon Sep 17 00:00:00 2001 From: Tim Holy Date: Mon, 29 Aug 2016 14:15:20 -0500 Subject: [PATCH] Add a more efficient implementation of in(::CartesianIndex, ::CartesianRange) (#18277) --- base/multidimensional.jl | 8 +++++++- test/arrayops.jl | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/base/multidimensional.jl b/base/multidimensional.jl index 0a2b9489cec51..10a495213f639 100644 --- a/base/multidimensional.jl +++ b/base/multidimensional.jl @@ -3,7 +3,7 @@ ### Multidimensional iterators module IteratorsMD -import Base: eltype, length, size, start, done, next, last, getindex, setindex!, linearindexing, min, max, zero, one, isless, eachindex, ndims, iteratorsize +import Base: eltype, length, size, start, done, next, last, in, getindex, setindex!, linearindexing, min, max, zero, one, isless, eachindex, ndims, iteratorsize importall ..Base.Operators import Base: simd_outer_range, simd_inner_length, simd_index using Base: LinearFast, LinearSlow, AbstractCartesianIndex, fill_to_length, tail @@ -130,6 +130,12 @@ length(iter::CartesianRange) = prod(size(iter)) last(iter::CartesianRange) = iter.stop +@inline function in{I<:CartesianIndex}(i::I, r::CartesianRange{I}) + _in(true, i.I, r.start.I, r.stop.I) +end +_in(b, ::Tuple{}, ::Tuple{}, ::Tuple{}) = b +@inline _in(b, i, start, stop) = _in(b & (start[1] <= i[1] <= stop[1]), tail(i), tail(start), tail(stop)) + simd_outer_range(iter::CartesianRange{CartesianIndex{0}}) = iter function simd_outer_range{I}(iter::CartesianRange{I}) start = CartesianIndex(tail(iter.start.I)) diff --git a/test/arrayops.jl b/test/arrayops.jl index 7b5e3f628213c..cb0a30d788a8f 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -1327,6 +1327,14 @@ indexes = collect(R) @test length(indexes) == 12 @test length(R) == 12 @test ndims(R) == 2 +@test in(CartesianIndex((2,3)), R) +@test in(CartesianIndex((3,3)), R) +@test in(CartesianIndex((3,5)), R) +@test in(CartesianIndex((5,5)), R) +@test !in(CartesianIndex((1,3)), R) +@test !in(CartesianIndex((3,2)), R) +@test !in(CartesianIndex((3,6)), R) +@test !in(CartesianIndex((6,5)), R) @test CartesianRange((3:5,-7:7)) == CartesianRange(CartesianIndex{2}(3,-7),CartesianIndex{2}(5,7)) @test CartesianRange((3,-7:7)) == CartesianRange(CartesianIndex{2}(3,-7),CartesianIndex{2}(3,7))