Skip to content

Commit

Permalink
Merge pull request #2 from yha/concrete-field
Browse files Browse the repository at this point in the history
Use concrete field type for type stability
  • Loading branch information
Vexatos committed Feb 3, 2020
2 parents 1a5834b + 159dcb4 commit 296b7b0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/CircularArrays.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ export CircularArray, CircularVector
array[index] == array[mod1(index, size)]
"""
struct CircularArray{T, N} <: AbstractArray{T, N}
data::AbstractArray{T, N}
struct CircularArray{T, N, A} <: AbstractArray{T, N}
data::A
CircularArray{T,N}(data::AbstractArray{T,N}) where {T,N} = new{T,N,typeof(data)}(data)
end

"""
Expand All @@ -28,6 +29,8 @@ const CircularVector{T} = CircularArray{T, 1}

@inline clamp_bounds(arr::CircularArray, I::Tuple{Vararg{Int}})::AbstractArray{Int, 1} = map(Base.splat(mod), zip(I, axes(arr.data)))

CircularArray(data::AbstractArray{T,N}) where {T,N} = CircularArray{T,N}(data)
CircularArray{T}(data::AbstractArray{T,N}) where {T,N} = CircularArray{T,N}(data)
CircularArray(def::T, size) where T = CircularArray(fill(def, size))

@inline Base.getindex(arr::CircularArray, i::Int) = @inbounds getindex(arr.data, mod(i, Base.axes1(arr.data)))
Expand Down
21 changes: 20 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,31 @@ using Test
@test IndexStyle(CircularArray) == IndexCartesian()
@test IndexStyle(CircularVector) == IndexLinear()

@testset "construction ($T)" for T = (Float64, Int)
data = rand(T,10)
arrays = [CircularVector(data), CircularVector{T}(data),
CircularArray(data), CircularArray{T}(data), CircularArray{T,1}(data)]
@test all(a == first(arrays) for a in arrays)
@test all(a isa CircularVector{T,Vector{T}} for a in arrays)
end

@testset "type stability $(n)d" for n in 1:10
a = CircularArray(fill(1, ntuple(_->1, n)))

@test @inferred(a[1]) isa Int64
@test @inferred(a[[1]]) isa CircularVector{Int64}
@test @inferred(a[[1]']) isa CircularArray{Int64,2}
@test @inferred(axes(a)) isa Tuple{Vararg{AbstractUnitRange}}
@test @inferred(similar(a)) isa typeof(a)
@test @inferred(a[a]) isa typeof(a)
end

@testset "vector" begin
data = rand(Int64, 5)
v1 = CircularVector(data)

@test size(v1, 1) == 5
@test typeof(v1) == CircularVector{Int64}
@test typeof(v1) == CircularVector{Int64,Vector{Int64}}
@test isa(v1, CircularVector)
@test isa(v1, AbstractVector{Int})
@test !isa(v1, AbstractVector{String})
Expand Down

0 comments on commit 296b7b0

Please sign in to comment.