Skip to content

Commit

Permalink
reduce allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
chrstphrbrns authored and tlnagy committed Jan 22, 2024
1 parent 220cc37 commit 764beb2
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 10 deletions.
17 changes: 9 additions & 8 deletions src/ifds.jl
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,10 @@ function reverse_prediction!(ifd::IFD, arr::AbstractArray{T,N}) where {T, N}

buffer::Vector{UInt8} = Vector{UInt8}(undef, columns)

valn = Val(sizeof(T))

temp2::Ptr{UInt8} = pointer(reinterpret(UInt8, arr))

for row in 1:rows
start = (row - 1) * columns
for plane in 1:spp
Expand All @@ -432,36 +435,34 @@ function reverse_prediction!(ifd::IFD, arr::AbstractArray{T,N}) where {T, N}
end
end
vw = view(reinterpret(UInt8, arr), start+1:start+columns)
deplane!(buffer, vw, sizeof(T))
deplane!(buffer, vw, valn)
end

arr .= bswap.(arr)
end
end
end

# {AAA...BBB...CCC...} => {ABCABCABC...}
function deplane!(arr::AbstractVector{T}, n::Integer) where T
out = Vector{T}(undef, length(arr))
deplane!(out, arr, n)
deplane!(out, arr, Val(n))
end

const is_mac_or_windows_x64 = (Sys.iswindows() || Sys.isapple()) && Sys.ARCH == :x86_64

# {AAA...BBB...CCC...} => {ABCABCABC...}
function deplane!(buffer::AbstractVector{T}, arr::AbstractVector{T}, n::Integer) where T
function deplane!(buffer::AbstractVector{T}, arr::AbstractVector{T}, n::Val{N}) where {T, N}
@assert length(buffer) == length(arr)
@assert length(arr) % n == 0
@assert length(arr) % N == 0

GC.@preserve arr buffer begin
if Int(pointer(arr)) & 0x3f > 0 || length(arr) < 64 || is_mac_or_windows_x64
# small or not 64-byte aligned
temp = deplane_slow(arr, n)
temp = deplane_slow(arr, N)
GC.@preserve temp begin
memcpy(pointer(arr), pointer(temp), sizeof(temp))
end
else
deplane_simd!(buffer, arr, Val(n))
deplane_simd!(buffer, arr, n)
memcpy(pointer(arr), pointer(buffer), sizeof(buffer))
end
end
Expand Down
2 changes: 1 addition & 1 deletion src/load.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function load(tf::TiffFile; verbose=true, mmap = false, lazyio = false)
end
end

if tf.need_bswap && !is_irregular_bps(ifd)
if (tf.need_bswap && !is_irregular_bps(ifd)) || predictor(ifd) == 3
@debug "bswap'ing data"
loaded .= bswap.(loaded)
end
Expand Down
2 changes: 1 addition & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ end
out = Vector{typ}(undef, size * planes)
a=reduce(vcat,[fill(typ(x),size) for x in 1:planes])
b=copy(a)
TiffImages.deplane!(out, a, planes)
TiffImages.deplane!(out, a, Val(planes))
@test a == TiffImages.deplane_slow(b, planes)
end
end
Expand Down

0 comments on commit 764beb2

Please sign in to comment.