Skip to content

Commit 4b60a84

Browse files
authored
[Containers] fix getindex when a custom subtype of <:Integer is used (#4056)
1 parent 77c40be commit 4b60a84

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/Containers/DenseAxisArray.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ function Base.getindex(
114114
x::_AxisLookup{Tuple{T,T}},
115115
key::Integer,
116116
) where {T<:Integer}
117+
if !isequal(key, convert(T, key))
118+
throw(KeyError(key))
119+
end
117120
i = key - x.data[1] + 1
118121
if !(1 <= i <= x.data[2])
119122
throw(KeyError(key))
@@ -133,6 +136,9 @@ function Base.get(
133136
key::Integer,
134137
default,
135138
) where {T<:Integer}
139+
if !isequal(key, convert(T, key))
140+
return default
141+
end
136142
i = key - x.data[1] + 1
137143
if !(1 <= i <= x.data[2])
138144
return default

test/Containers/test_DenseAxisArray.jl

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -952,4 +952,46 @@ function test_conntainer_AbstractUnitRange_Integer()
952952
return
953953
end
954954

955+
struct Int4053 <: Integer
956+
x::Int
957+
end
958+
959+
Int4053(f::Int4053) = f
960+
961+
Base.:<(a::Int4053, b::Int4053) = a.x < b.x
962+
963+
Base.:<=(a::Int4053, b::Int4053) = a.x <= b.x
964+
965+
Base.:+(a::Int4053, b::Int4053) = Int4053(a.x + b.x)
966+
967+
Base.:-(a::Int4053, b::Int4053) = Int4053(a.x - b.x)
968+
969+
Base.:(==)(a::Int4053, b::Int4053) = a.x == b.x
970+
971+
Base.hash(a::Int4053, h::UInt) = hash((Int4053, a.x), h)
972+
973+
Base.:(==)(a::Int4053, b::Integer) = false
974+
975+
Base.:(==)(a::Integer, b::Int4053) = false
976+
977+
Base.promote_rule(T::Type{<:Integer}, ::Type{Int4053}) = T
978+
979+
Base.Int(x::Int4053) = x.x
980+
981+
function test_issue_4053()
982+
Containers.@container(A[i in Int4053(1):Int4053(3)], i.x)
983+
@test_throws KeyError A[1]
984+
@test !isassigned(A, 1)
985+
@test_throws KeyError A[0x01]
986+
@test !isassigned(A, 0x01)
987+
@test A[Int4053(1)] === 1
988+
@test isassigned(A, Int4053(1))
989+
Containers.@container(B[i in 2:4], i)
990+
@test B[2] === 2
991+
@test B[0x02] === 2
992+
@test_throws KeyError B[Int4053(2)]
993+
@test !isassigned(B, Int4053(2))
994+
return
995+
end
996+
955997
end # module

0 commit comments

Comments
 (0)