• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / 1405

29 Aug 2025 03:48AM UTC coverage: 74.829% (-1.3%) from 76.086%
1405

push

buildkite

web-flow
make NEWS-update.jl more robust in trimming existing links (#59305)

The `NEWS-update.jl` script trims away any existing links from the end
of the `NEWS.md` file, so that it is safe to run multiple times. This PR
makes that trimming a bit more robust by trimming only `[#...]:`
patterns that start at the beginning of a line.

(I ran into this in re-using the same script for another project.)

63849 of 85327 relevant lines covered (74.83%)

21422751.51 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.85
/base/reinterpretarray.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
"""
4
Gives a reinterpreted view (of element type T) of the underlying array (of element type S).
5
If the size of `T` differs from the size of `S`, the array will be compressed/expanded in
6
the first dimension. The variant `reinterpret(reshape, T, a)` instead adds or consumes the first dimension
7
depending on the ratio of element sizes.
8
"""
9
struct ReinterpretArray{T,N,S,A<:AbstractArray{S},IsReshaped} <: AbstractArray{T, N}
10
    parent::A
11
    readable::Bool
12
    writable::Bool
13

14
    function throwbits(S::Type, T::Type, U::Type)
×
15
        @noinline
×
16
        throw(ArgumentError(LazyString("cannot reinterpret `", S, "` as `", T, "`, type `", U, "` is not a bits type")))
×
17
    end
18
    function throwsize0(S::Type, T::Type, msg)
15✔
19
        @noinline
15✔
20
        throw(ArgumentError(LazyString("cannot reinterpret a zero-dimensional `", S, "` array to `", T,
15✔
21
            "` which is of a ", msg, " size")))
22
    end
23
    function throwsingleton(S::Type, T::Type)
×
24
        @noinline
×
25
        throw(ArgumentError(LazyString("cannot reinterpret a `", S, "` array to `", T, "` which is a singleton type")))
×
26
    end
27

28
    global reinterpret
29

30
    @doc """
31
        reinterpret(T::DataType, A::AbstractArray)
32

33
    Construct a view of the array with the same binary data as the given
34
    array, but with `T` as element type.
35

36
    This function also works on "lazy" array whose elements are not computed until they are explicitly retrieved.
37
    For instance, `reinterpret` on the range `1:6` works similarly as on the dense vector `collect(1:6)`:
38

39
    ```jldoctest
40
    julia> reinterpret(Float32, UInt32[1 2 3 4 5])
41
    1×5 reinterpret(Float32, ::Matrix{UInt32}):
42
     1.0f-45  3.0f-45  4.0f-45  6.0f-45  7.0f-45
43

44
    julia> reinterpret(Complex{Int}, 1:6)
45
    3-element reinterpret(Complex{$Int}, ::UnitRange{$Int}):
46
     1 + 2im
47
     3 + 4im
48
     5 + 6im
49
    ```
50

51
    If the location of padding bits does not line up between `T` and `eltype(A)`, the resulting array will be
52
    read-only or write-only, to prevent invalid bits from being written to or read from, respectively.
53

54
    ```jldoctest
55
    julia> a = reinterpret(Tuple{UInt8, UInt32}, UInt32[1, 2])
56
    1-element reinterpret(Tuple{UInt8, UInt32}, ::Vector{UInt32}):
57
     (0x01, 0x00000002)
58

59
    julia> a[1] = 3
60
    ERROR: Padding of type Tuple{UInt8, UInt32} is not compatible with type UInt32.
61

62
    julia> b = reinterpret(UInt32, Tuple{UInt8, UInt32}[(0x01, 0x00000002)]); # showing will error
63

64
    julia> b[1]
65
    ERROR: Padding of type UInt32 is not compatible with type Tuple{UInt8, UInt32}.
66
    ```
67
    """
68
    function reinterpret(::Type{T}, a::A) where {T,N,S,A<:AbstractArray{S, N}}
2,546✔
69
        function thrownonint(S::Type, T::Type, dim)
199,238✔
70
            @noinline
×
71
            throw(ArgumentError(LazyString(
×
72
                "cannot reinterpret an `", S, "` array to `", T, "` whose first dimension has size `", dim,
73
                "`. The resulting array would have a non-integral first dimension.")))
74
        end
75
        function throwaxes1(S::Type, T::Type, ax1)
199,244✔
76
            @noinline
6✔
77
            throw(ArgumentError(LazyString("cannot reinterpret a `", S, "` array to `", T,
6✔
78
                "` when the first axis is ", ax1, ". Try reshaping first.")))
79
        end
80
        isbitstype(T) || throwbits(S, T, T)
199,238✔
81
        isbitstype(S) || throwbits(S, T, S)
199,229✔
82
        (N != 0 || sizeof(T) == sizeof(S)) || throwsize0(S, T, "different")
199,220✔
83
        if N != 0 && sizeof(S) != sizeof(T)
199,208✔
84
            ax1 = axes(a)[1]
201,163✔
85
            dim = length(ax1)
197,855✔
86
            if issingletontype(T)
197,855✔
87
                issingletontype(S) || throwsingleton(S, T)
6✔
88
            else
89
                rem(dim*sizeof(S),sizeof(T)) == 0 || thrownonint(S, T, dim)
201,047✔
90
            end
91
            first(ax1) == 1 || throwaxes1(S, T, ax1)
197,849✔
92
        end
93
        readable = array_subpadding(T, S)
199,190✔
94
        writable = array_subpadding(S, T)
199,190✔
95
        new{T, N, S, A, false}(a, readable, writable)
209,930✔
96
    end
97
    reinterpret(::Type{T}, a::AbstractArray{T}) where {T} = a
464✔
98

99
    # With reshaping
100
    function reinterpret(::typeof(reshape), ::Type{T}, a::A) where {T,S,A<:AbstractArray{S}}
284✔
101
        function throwintmult(S::Type, T::Type)
2,815✔
102
            @noinline
103
            throw(ArgumentError(LazyString("`reinterpret(reshape, T, a)` requires that one of `sizeof(T)` (got ",
104
                sizeof(T), ") and `sizeof(eltype(a))` (got ", sizeof(S), ") be an integer multiple of the other")))
105
        end
106
        function throwsize1(a::AbstractArray, T::Type)
2,821✔
107
            @noinline
6✔
108
            throw(ArgumentError(LazyString("`reinterpret(reshape, ", T, ", a)` where `eltype(a)` is ", eltype(a),
6✔
109
                " requires that `axes(a, 1)` (got ", axes(a, 1), ") be equal to 1:",
110
                sizeof(T) ÷ sizeof(eltype(a)), " (from the ratio of element sizes)")))
111
        end
112
        function throwfromsingleton(S, T)
2,824✔
113
            @noinline
9✔
114
            throw(ArgumentError(LazyString("`reinterpret(reshape, ", T, ", a)` where `eltype(a)` is ", S,
9✔
115
                " requires that ", T, " be a singleton type, since ", S, " is one")))
116
        end
117
        isbitstype(T) || throwbits(S, T, T)
2,815✔
118
        isbitstype(S) || throwbits(S, T, S)
2,809✔
119
        if sizeof(S) == sizeof(T)
2,806✔
120
            N = ndims(a)
197✔
121
        elseif sizeof(S) > sizeof(T)
2,609✔
122
            issingletontype(T) && throwsingleton(S, T)
2,412✔
123
            rem(sizeof(S), sizeof(T)) == 0 || throwintmult(S, T)
2,403✔
124
            N = ndims(a) + 1
2,403✔
125
        else
126
            issingletontype(S) && throwfromsingleton(S, T)
197✔
127
            rem(sizeof(T), sizeof(S)) == 0 || throwintmult(S, T)
188✔
128
            N = ndims(a) - 1
185✔
129
            N > -1 || throwsize0(S, T, "larger")
185✔
130
            axes(a, 1) == OneTo(sizeof(T) ÷ sizeof(S)) || throwsize1(a, T)
188✔
131
        end
132
        readable = array_subpadding(T, S)
2,776✔
133
        writable = array_subpadding(S, T)
2,776✔
134
        new{T, N, S, A, true}(a, readable, writable)
2,776✔
135
    end
136
    reinterpret(::typeof(reshape), ::Type{T}, a::AbstractArray{T}) where {T} = a
6✔
137
end
138

139
ReshapedReinterpretArray{T,N,S,A<:AbstractArray{S}} = ReinterpretArray{T,N,S,A,true}
140
NonReshapedReinterpretArray{T,N,S,A<:AbstractArray{S, N}} = ReinterpretArray{T,N,S,A,false}
141

142
"""
143
    reinterpret(reshape, T, A::AbstractArray{S}) -> B
144

145
Change the type-interpretation of `A` while consuming or adding a "channel dimension."
146

147
If `sizeof(T) = n*sizeof(S)` for `n>1`, `A`'s first dimension must be
148
of size `n` and `B` lacks `A`'s first dimension. Conversely, if `sizeof(S) = n*sizeof(T)` for `n>1`,
149
`B` gets a new first dimension of size `n`. The dimensionality is unchanged if `sizeof(T) == sizeof(S)`.
150

151
!!! compat "Julia 1.6"
152
    This method requires at least Julia 1.6.
153

154
# Examples
155

156
```jldoctest
157
julia> A = [1 2; 3 4]
158
2×2 Matrix{$Int}:
159
 1  2
160
 3  4
161

162
julia> reinterpret(reshape, Complex{Int}, A)    # the result is a vector
163
2-element reinterpret(reshape, Complex{$Int}, ::Matrix{$Int}) with eltype Complex{$Int}:
164
 1 + 3im
165
 2 + 4im
166

167
julia> a = [(1,2,3), (4,5,6)]
168
2-element Vector{Tuple{$Int, $Int, $Int}}:
169
 (1, 2, 3)
170
 (4, 5, 6)
171

172
julia> reinterpret(reshape, Int, a)             # the result is a matrix
173
3×2 reinterpret(reshape, $Int, ::Vector{Tuple{$Int, $Int, $Int}}) with eltype $Int:
174
 1  4
175
 2  5
176
 3  6
177
```
178
"""
179
reinterpret(::typeof(reshape), T::Type, a::AbstractArray)
180

181
reinterpret(::Type{T}, a::NonReshapedReinterpretArray) where {T} = reinterpret(T, a.parent)
463✔
182
reinterpret(::typeof(reshape), ::Type{T}, a::ReshapedReinterpretArray) where {T} = reinterpret(reshape, T, a.parent)
6✔
183

184
# Definition of StridedArray
185
StridedFastContiguousSubArray{T,N,A<:DenseArray} = FastContiguousSubArray{T,N,A}
186
StridedReinterpretArray{T,N,A<:Union{DenseArray,StridedFastContiguousSubArray},IsReshaped} = ReinterpretArray{T,N,S,A,IsReshaped} where S
187
StridedReshapedArray{T,N,A<:Union{DenseArray,StridedFastContiguousSubArray,StridedReinterpretArray}} = ReshapedArray{T,N,A}
188
StridedSubArray{T,N,A<:Union{DenseArray,StridedReshapedArray,StridedReinterpretArray},
189
    I<:Tuple{Vararg{Union{RangeIndex, ReshapedUnitRange, AbstractCartesianIndex}}}} = SubArray{T,N,A,I}
190
StridedArray{T,N} = Union{DenseArray{T,N}, StridedSubArray{T,N}, StridedReshapedArray{T,N}, StridedReinterpretArray{T,N}}
191
StridedVector{T} = StridedArray{T,1}
192
StridedMatrix{T} = StridedArray{T,2}
193
StridedVecOrMat{T} = Union{StridedVector{T}, StridedMatrix{T}}
194

195
strides(a::Union{DenseArray,StridedReshapedArray,StridedReinterpretArray}) = size_to_strides(1, size(a)...)
72,983,316✔
196
stride(A::Union{DenseArray,StridedReshapedArray,StridedReinterpretArray}, k::Integer) =
48,580,611✔
197
    k ≤ ndims(A) ? strides(A)[k] : length(A)
198

199
function strides(a::ReinterpretArray{T,<:Any,S,<:AbstractArray{S},IsReshaped}) where {T,S,IsReshaped}
303✔
200
    _checkcontiguous(Bool, a) && return size_to_strides(1, size(a)...)
9,381✔
201
    stp = strides(parent(a))
9,318✔
202
    els, elp = sizeof(T), sizeof(S)
9,318✔
203
    els == elp && return stp # 0dim parent is also handled here.
9,318✔
204
    IsReshaped && els < elp && return (1, _checked_strides(stp, els, elp)...)
5,928✔
205
    stp[1] == 1 || throw(ArgumentError("Parent must be contiguous in the 1st dimension!"))
2,010✔
206
    st′ = _checked_strides(tail(stp), els, elp)
1,935✔
207
    return IsReshaped ? st′ : (1, st′...)
1,821✔
208
end
209

210
@inline function _checked_strides(stp::Tuple, els::Integer, elp::Integer)
211
    if elp > els && rem(elp, els) == 0
5,862✔
212
        N = div(elp, els)
5,391✔
213
        return map(i -> N * i, stp)
12,630✔
214
    end
215
    drs = map(i -> divrem(elp * i, els), stp)
942✔
216
    all(i->iszero(i[2]), drs) ||
1,179✔
217
        throw(ArgumentError("Parent's strides could not be exactly divided!"))
218
    map(first, drs)
414✔
219
end
220

221
_checkcontiguous(::Type{Bool}, A::ReinterpretArray) = _checkcontiguous(Bool, parent(A))
14,240✔
222

223
similar(a::ReinterpretArray, T::Type, d::Dims) = similar(a.parent, T, d)
197,377✔
224
similar(::Type{TA}, dims::Dims) where {T,N,O,P,TA<:ReinterpretArray{T,N,O,P}} = similar(P, dims)
3✔
225

226
function check_readable(a::ReinterpretArray{T, N, S} where N) where {T,S}
6✔
227
    # See comment in check_writable
228
    if !a.readable && !array_subpadding(T, S)
5,240,339✔
229
        throw(PaddingError(T, S))
6✔
230
    end
231
end
232

233
function check_writable(a::ReinterpretArray{T, N, S} where N) where {T,S}
234
    # `array_subpadding` is relatively expensive (compared to a simple arrayref),
235
    # so it is cached in the array. However, it is computable at compile time if,
236
    # inference has the types available. By using this form of the check, we can
237
    # get the best of both worlds for the success case. If the types were not
238
    # available to inference, we simply need to check the field (relatively cheap)
239
    # and if they were we should be able to fold this check away entirely.
240
    if !a.writable && !array_subpadding(S, T)
123,362,899✔
241
        throw(PaddingError(T, S))
6✔
242
    end
243
end
244

245
## IndexStyle specializations
246

247
# For `reinterpret(reshape, T, a)` where we're adding a channel dimension and with
248
# `IndexStyle(a) == IndexLinear()`, it's advantageous to retain pseudo-linear indexing.
249
struct IndexSCartesian2{K} <: IndexStyle end   # K = sizeof(S) ÷ sizeof(T), a static-sized 2d cartesian iterator
6,369✔
250

251
IndexStyle(::Type{ReinterpretArray{T,N,S,A,false}}) where {T,N,S,A<:AbstractArray{S,N}} = IndexStyle(A)
402,021✔
252
function IndexStyle(::Type{ReinterpretArray{T,N,S,A,true}}) where {T,N,S,A<:AbstractArray{S}}
253
    if sizeof(T) < sizeof(S)
12,699✔
254
        IndexStyle(A) === IndexLinear() && return IndexSCartesian2{sizeof(S) ÷ sizeof(T)}()
9,947✔
255
        return IndexCartesian()
3,590✔
256
    end
257
    return IndexStyle(A)
2,752✔
258
end
259
IndexStyle(::IndexSCartesian2{K}, ::IndexSCartesian2{K}) where {K} = IndexSCartesian2{K}()
9✔
260

261
struct SCartesianIndex2{K}   # can't make <:AbstractCartesianIndex without N, and 2 would be a bit misleading
262
    i::Int
24,889✔
263
    j::Int
264
end
265
to_index(i::SCartesianIndex2) = i
252✔
266

267
struct SCartesianIndices2{K,R<:AbstractUnitRange{Int}} <: AbstractMatrix{SCartesianIndex2{K}}
268
    indices2::R
122✔
269
end
270
SCartesianIndices2{K}(indices2::AbstractUnitRange{Int}) where {K} = (@assert K::Int > 1; SCartesianIndices2{K,typeof(indices2)}(indices2))
122✔
271

272
eachindex(::IndexSCartesian2{K}, A::ReshapedReinterpretArray) where {K} = SCartesianIndices2{K}(eachindex(IndexLinear(), parent(A)))
114✔
273
@inline function eachindex(style::IndexSCartesian2{K}, A::AbstractArray, B::AbstractArray...) where {K}
274
    iter = eachindex(style, A)
9✔
275
    itersBs = map(C->eachindex(style, C), B)
18✔
276
    all(==(iter), itersBs) || throw_eachindex_mismatch_indices("axes", axes(A), map(axes, B)...)
9✔
277
    return iter
9✔
278
end
279

280
size(iter::SCartesianIndices2{K}) where K = (K, length(iter.indices2))
12✔
281
axes(iter::SCartesianIndices2{K}) where K = (OneTo(K), iter.indices2)
27✔
282

283
first(iter::SCartesianIndices2{K}) where {K} = SCartesianIndex2{K}(1, first(iter.indices2))
14✔
284
last(iter::SCartesianIndices2{K}) where {K}  = SCartesianIndex2{K}(K, last(iter.indices2))
27✔
285

286
@inline function getindex(iter::SCartesianIndices2{K}, i::Int, j::Int) where {K}
×
287
    @boundscheck checkbounds(iter, i, j)
×
288
    return SCartesianIndex2{K}(i, iter.indices2[j])
×
289
end
290

291
function iterate(iter::SCartesianIndices2{K}) where {K}
292
    ret = iterate(iter.indices2)
106✔
293
    ret === nothing && return nothing
104✔
294
    item2, state2 = ret
104✔
295
    return SCartesianIndex2{K}(1, item2), (1, item2, state2)
104✔
296
end
297

298
function iterate(iter::SCartesianIndices2{K}, (state1, item2, state2)) where {K}
299
    if state1 < K
750✔
300
        item1 = state1 + 1
465✔
301
        return SCartesianIndex2{K}(item1, item2), (item1, item2, state2)
465✔
302
    end
303
    ret = iterate(iter.indices2, state2)
502✔
304
    ret === nothing && return nothing
285✔
305
    item2, state2 = ret
217✔
306
    return SCartesianIndex2{K}(1, item2), (1, item2, state2)
217✔
307
end
308

309
SimdLoop.simd_outer_range(iter::SCartesianIndices2) = iter.indices2
×
310
SimdLoop.simd_inner_length(::SCartesianIndices2{K}, ::Any) where K = K
×
311
@inline function SimdLoop.simd_index(::SCartesianIndices2{K}, Ilast::Int, I1::Int) where {K}
×
312
    SCartesianIndex2{K}(I1+1, Ilast)
×
313
end
314

315
_maybe_reshape(::IndexSCartesian2, A::AbstractArray, I...) = _maybe_reshape(IndexCartesian(), A, I...)
3✔
316
_maybe_reshape(::IndexSCartesian2, A::ReshapedReinterpretArray, I...) = A
12✔
317

318
# fallbacks
319
function _getindex(::IndexSCartesian2, A::AbstractArray, I::Vararg{Int, N}) where {N}
320
    @_propagate_inbounds_meta
198✔
321
    _getindex(IndexCartesian(), A, I...)
198✔
322
end
323
function _setindex!(::IndexSCartesian2, A::AbstractArray, v, I::Vararg{Int, N}) where {N}
×
324
    @_propagate_inbounds_meta
×
325
    _setindex!(IndexCartesian(), A, v, I...)
×
326
end
327
# fallbacks for array types that use "pass-through" indexing (e.g., `IndexStyle(A) = IndexStyle(parent(A))`)
328
# but which don't handle SCartesianIndex2
329
function _getindex(::IndexSCartesian2, A::AbstractArray{T,N}, ind::SCartesianIndex2) where {T,N}
×
330
    @_propagate_inbounds_meta
×
331
    J = _ind2sub(tail(axes(A)), ind.j)
×
332
    getindex(A, ind.i, J...)
×
333
end
334

335
function _getindex(::IndexSCartesian2{2}, A::AbstractArray{T,2}, ind::SCartesianIndex2) where {T}
336
    @_propagate_inbounds_meta
90✔
337
    J = first(axes(A, 2)) + ind.j - 1
90✔
338
    getindex(A, ind.i, J)
90✔
339
end
340

341
function _setindex!(::IndexSCartesian2, A::AbstractArray{T,N}, v, ind::SCartesianIndex2) where {T,N}
342
    @_propagate_inbounds_meta
72✔
343
    J = _ind2sub(tail(axes(A)), ind.j)
72✔
344
    setindex!(A, v, ind.i, J...)
72✔
345
end
346

347
function _setindex!(::IndexSCartesian2{2}, A::AbstractArray{T,2}, v, ind::SCartesianIndex2) where {T}
348
    @_propagate_inbounds_meta
90✔
349
    J = first(axes(A, 2)) + ind.j - 1
90✔
350
    setindex!(A, v, ind.i, J)
90✔
351
end
352

353
eachindex(style::IndexSCartesian2, A::AbstractArray) = eachindex(style, parent(A))
54✔
354

355
## AbstractArray interface
356

357
parent(a::ReinterpretArray) = a.parent
5,935,882✔
358
dataids(a::ReinterpretArray) = dataids(a.parent)
18,859✔
359
unaliascopy(a::NonReshapedReinterpretArray{T}) where {T} = reinterpret(T, unaliascopy(a.parent))
6✔
360
unaliascopy(a::ReshapedReinterpretArray{T}) where {T} = reinterpret(reshape, T, unaliascopy(a.parent))
3✔
361

362
function size(a::NonReshapedReinterpretArray{T,N,S} where {N}) where {T,S}
18✔
363
    psize = size(a.parent)
44,305✔
364
    size1 = issingletontype(T) ? psize[1] : div(psize[1]*sizeof(S), sizeof(T))
44,218✔
365
    tuple(size1, tail(psize)...)
44,218✔
366
end
367
function size(a::ReshapedReinterpretArray{T,N,S} where {N}) where {T,S}
21✔
368
    psize = size(a.parent)
12,738✔
369
    sizeof(S) > sizeof(T) && return (div(sizeof(S), sizeof(T)), psize...)
12,636✔
370
    sizeof(S) < sizeof(T) && return tail(psize)
1,425✔
371
    return psize
599✔
372
end
373
size(a::NonReshapedReinterpretArray{T,0}) where {T} = ()
158✔
374

375
function axes(a::NonReshapedReinterpretArray{T,N,S} where {N}) where {T,S}
1,446✔
376
    paxs = axes(a.parent)
5,076,265✔
377
    f, l = first(paxs[1]), length(paxs[1])
4,912,261✔
378
    size1 = issingletontype(T) ? l : div(l*sizeof(S), sizeof(T))
5,067,829✔
379
    tuple(oftype(paxs[1], f:f+size1-1), tail(paxs)...)
5,067,829✔
380
end
381
function axes(a::ReshapedReinterpretArray{T,N,S} where {N}) where {T,S}
4,230✔
382
    paxs = axes(a.parent)
67,062✔
383
    sizeof(S) > sizeof(T) && return (OneTo(div(sizeof(S), sizeof(T))), paxs...)
48,102✔
384
    sizeof(S) < sizeof(T) && return tail(paxs)
6,878✔
385
    return paxs
5,457✔
386
end
387
axes(a::NonReshapedReinterpretArray{T,0}) where {T} = ()
18✔
388

389
has_offset_axes(a::ReinterpretArray) = has_offset_axes(a.parent)
282✔
390

391
elsize(::Type{<:ReinterpretArray{T}}) where {T} = sizeof(T)
5,925,034✔
392
cconvert(::Type{Ptr{T}}, a::ReinterpretArray{T,N,S} where N) where {T,S} = cconvert(Ptr{S}, a.parent)
4,396,366✔
393
unsafe_convert(::Type{Ptr{T}}, a::ReinterpretArray{T,N,S} where N) where {T,S} = Ptr{T}(unsafe_convert(Ptr{S},a.parent))
6✔
394

395
@propagate_inbounds function getindex(a::NonReshapedReinterpretArray{T,0,S}) where {T,S}
3✔
396
    if isprimitivetype(T) && isprimitivetype(S)
45✔
397
        reinterpret(T, a.parent[])
18✔
398
    else
399
        a[firstindex(a)]
27✔
400
    end
401
end
402

403
check_ptr_indexable(a::ReinterpretArray, sz = elsize(a)) = check_ptr_indexable(parent(a), sz)
11,824,262✔
404
check_ptr_indexable(a::ReshapedArray, sz) = check_ptr_indexable(parent(a), sz)
1,482✔
405
check_ptr_indexable(a::FastContiguousSubArray, sz) = check_ptr_indexable(parent(a), sz)
922,140✔
406
check_ptr_indexable(a::Array, sz) = sizeof(eltype(a)) !== sz
4,941,614✔
407
check_ptr_indexable(a::Memory, sz) = true
×
408
check_ptr_indexable(a::AbstractArray, sz) = false
×
409

410
@propagate_inbounds getindex(a::ReshapedReinterpretArray{T,0}) where {T} = a[firstindex(a)]
120✔
411

412
@propagate_inbounds isassigned(a::ReinterpretArray, inds::Integer...) = checkbounds(Bool, a, inds...) && (check_ptr_indexable(a) || _isassigned_ra(a, inds...))
36✔
413
@propagate_inbounds isassigned(a::ReinterpretArray, inds::SCartesianIndex2) = isassigned(a.parent, inds.j)
×
414
@propagate_inbounds _isassigned_ra(a::ReinterpretArray, inds...) = true # that is not entirely true, but computing exactly which indexes will be accessed in the parent requires a lot of duplication from the _getindex_ra code
×
415

416
@propagate_inbounds function getindex(a::ReinterpretArray{T,N,S}, inds::Vararg{Int, N}) where {T,N,S}
276✔
417
    check_readable(a)
12,095,073✔
418
    check_ptr_indexable(a) && return _getindex_ptr(a, inds...)
12,250,635✔
419
    _getindex_ra(a, inds[1], tail(inds))
120,946,801✔
420
end
421

422
@propagate_inbounds function getindex(a::ReinterpretArray{T,N,S}, i::Int) where {T,N,S}
108✔
423
    check_readable(a)
29,047✔
424
    check_ptr_indexable(a) && return _getindex_ptr(a, i)
29,047✔
425
    if isa(IndexStyle(a), IndexLinear)
10,310✔
426
        return _getindex_ra(a, i, ())
2,000✔
427
    end
428
    # Convert to full indices here, to avoid needing multiple conversions in
429
    # the loop in _getindex_ra
430
    inds = _to_subscript_indices(a, i)
14,076✔
431
    isempty(inds) ? _getindex_ra(a, firstindex(a), ()) : _getindex_ra(a, inds[1], tail(inds))
8,652✔
432
end
433

434
@propagate_inbounds function getindex(a::ReshapedReinterpretArray{T,N,S}, ind::SCartesianIndex2) where {T,N,S}
435
    check_readable(a)
24,204✔
436
    s = Ref{S}(a.parent[ind.j])
24,204✔
437
    tptr = Ptr{T}(unsafe_convert(Ref{S}, s))
24,204✔
438
    GC.@preserve s return unsafe_load(tptr, ind.i)
24,204✔
439
end
440

441
@inline function _getindex_ptr(a::ReinterpretArray{T}, inds...) where {T}
442
    @boundscheck checkbounds(a, inds...)
4,380,683✔
443
    li = _to_linear_index(a, inds...)
4,225,079✔
444
    ap = cconvert(Ptr{T}, a)
4,380,647✔
445
    p = unsafe_convert(Ptr{T}, ap) + sizeof(T) * (li - 1)
4,380,647✔
446
    GC.@preserve ap return unsafe_load(p)
4,380,647✔
447
end
448

449
@propagate_inbounds function _getindex_ra(a::NonReshapedReinterpretArray{T,N,S}, i1::Int, tailinds::TT) where {T,N,S,TT}
450
    # Make sure to match the scalar reinterpret if that is applicable
451
    if sizeof(T) == sizeof(S) && (fieldcount(T) + fieldcount(S)) == 0
7,892,978✔
452
        if issingletontype(T) # singleton types
7,888,139✔
453
            @boundscheck checkbounds(a, i1, tailinds...)
279✔
454
            return T.instance
261✔
455
        end
456
        return reinterpret(T, a.parent[i1, tailinds...])
120,945,497✔
457
    else
458
        @boundscheck checkbounds(a, i1, tailinds...)
4,893✔
459
        ind_start, sidx = divrem((i1-1)*sizeof(T), sizeof(S))
4,785✔
460
        # Optimizations that avoid branches
461
        if sizeof(T) % sizeof(S) == 0
4,785✔
462
            # T is bigger than S and contains an integer number of them
463
            n = sizeof(T) ÷ sizeof(S)
244✔
464
            t = Ref{T}()
244✔
465
            GC.@preserve t begin
244✔
466
                sptr = Ptr{S}(unsafe_convert(Ref{T}, t))
244✔
467
                for i = 1:n
244✔
468
                     s = a.parent[ind_start + i, tailinds...]
410✔
469
                     unsafe_store!(sptr, s, i)
386✔
470
                end
528✔
471
            end
472
            return t[]
244✔
473
        elseif sizeof(S) % sizeof(T) == 0
4,541✔
474
            # S is bigger than T and contains an integer number of them
475
            s = Ref{S}(a.parent[ind_start + 1, tailinds...])
4,505✔
476
            GC.@preserve s begin
4,433✔
477
                tptr = Ptr{T}(unsafe_convert(Ref{S}, s))
4,433✔
478
                return unsafe_load(tptr + sidx)
4,433✔
479
            end
480
        else
481
            i = 1
108✔
482
            nbytes_copied = 0
108✔
483
            # This is a bit complicated to deal with partial elements
484
            # at both the start and the end. LLVM will fold as appropriate,
485
            # once it knows the data layout
486
            s = Ref{S}()
108✔
487
            t = Ref{T}()
108✔
488
            GC.@preserve s t begin
108✔
489
                sptr = Ptr{S}(unsafe_convert(Ref{S}, s))
108✔
490
                tptr = Ptr{T}(unsafe_convert(Ref{T}, t))
108✔
491
                while nbytes_copied < sizeof(T)
348✔
492
                    s[] = a.parent[ind_start + i, tailinds...]
252✔
493
                    nb = min(sizeof(S) - sidx, sizeof(T)-nbytes_copied)
240✔
494
                    memcpy(tptr + nbytes_copied, sptr + sidx, nb)
240✔
495
                    nbytes_copied += nb
240✔
496
                    sidx = 0
240✔
497
                    i += 1
240✔
498
                end
348✔
499
            end
500
            return t[]
108✔
501
        end
502
    end
503
end
504

505
@propagate_inbounds function _getindex_ra(a::ReshapedReinterpretArray{T,N,S}, i1::Int, tailinds::TT) where {T,N,S,TT}
506
    # Make sure to match the scalar reinterpret if that is applicable
507
    if sizeof(T) == sizeof(S) && (fieldcount(T) + fieldcount(S)) == 0
6,039✔
508
        if issingletontype(T) # singleton types
2,067✔
509
            @boundscheck checkbounds(a, i1, tailinds...)
192✔
510
            return T.instance
186✔
511
        end
512
        return reinterpret(T, a.parent[i1, tailinds...])
1,878✔
513
    end
514
    @boundscheck checkbounds(a, i1, tailinds...)
3,972✔
515
    if sizeof(T) >= sizeof(S)
3,972✔
516
        t = Ref{T}()
366✔
517
        GC.@preserve t begin
366✔
518
            sptr = Ptr{S}(unsafe_convert(Ref{T}, t))
366✔
519
            if sizeof(T) > sizeof(S)
366✔
520
                # Extra dimension in the parent array
521
                n = sizeof(T) ÷ sizeof(S)
342✔
522
                if isempty(tailinds) && IndexStyle(a.parent) === IndexLinear()
342✔
523
                    offset = n * (i1 - firstindex(a))
96✔
524
                    for i = 1:n
96✔
525
                        s = a.parent[i + offset]
468✔
526
                        unsafe_store!(sptr, s, i)
468✔
527
                    end
840✔
528
                else
529
                    for i = 1:n
246✔
530
                        s = a.parent[i, i1, tailinds...]
552✔
531
                        unsafe_store!(sptr, s, i)
492✔
532
                    end
738✔
533
                end
534
            else
535
                # No extra dimension
536
                s = a.parent[i1, tailinds...]
24✔
537
                unsafe_store!(sptr, s)
366✔
538
            end
539
        end
540
        return t[]
366✔
541
    end
542
    # S is bigger than T and contains an integer number of them
543
    # n = sizeof(S) ÷ sizeof(T)
544
    s = Ref{S}()
3,606✔
545
    GC.@preserve s begin
3,606✔
546
        tptr = Ptr{T}(unsafe_convert(Ref{S}, s))
3,606✔
547
        s[] = a.parent[tailinds...]
3,642✔
548
        return unsafe_load(tptr, i1)
3,606✔
549
    end
550
end
551

552
@propagate_inbounds function setindex!(a::NonReshapedReinterpretArray{T,0,S}, v) where {T,S}
6✔
553
    if isprimitivetype(S) && isprimitivetype(T)
39✔
554
        a.parent[] = reinterpret(S, convert(T, v)::T)
15✔
555
        return a
9✔
556
    end
557
    setindex!(a, v, firstindex(a))
24✔
558
end
559

560
@propagate_inbounds setindex!(a::ReshapedReinterpretArray{T,0}, v) where {T} = setindex!(a, v, firstindex(a))
84✔
561

562
@propagate_inbounds function setindex!(a::ReinterpretArray{T,N,S}, v, inds::Vararg{Int, N}) where {T,N,S}
171✔
563
    check_writable(a)
123,748,792✔
564
    check_ptr_indexable(a) && return _setindex_ptr!(a, v, inds...)
123,748,786✔
565
    _setindex_ra!(a, v, inds[1], tail(inds))
123,795,844✔
566
end
567

568
@propagate_inbounds function setindex!(a::ReinterpretArray{T,N,S}, v, i::Int) where {T,N,S}
102✔
569
    check_writable(a)
540✔
570
    check_ptr_indexable(a) && return _setindex_ptr!(a, v, i)
540✔
571
    if isa(IndexStyle(a), IndexLinear)
411✔
572
        return _setindex_ra!(a, v, i, ())
321✔
573
    end
574
    inds = _to_subscript_indices(a, i)
156✔
575
    isempty(inds) ? _setindex_ra!(a, v, firstindex(a), ()) : _setindex_ra!(a, v, inds[1], tail(inds))
168✔
576
end
577

578
@propagate_inbounds function setindex!(a::ReshapedReinterpretArray{T,N,S}, v, ind::SCartesianIndex2) where {T,N,S}
579
    check_writable(a)
15✔
580
    v = convert(T, v)::T
15✔
581
    s = Ref{S}(a.parent[ind.j])
15✔
582
    GC.@preserve s begin
15✔
583
        tptr = Ptr{T}(unsafe_convert(Ref{S}, s))
15✔
584
        unsafe_store!(tptr, v, ind.i)
15✔
585
    end
586
    a.parent[ind.j] = s[]
15✔
587
    return a
15✔
588
end
589

590
@inline function _setindex_ptr!(a::ReinterpretArray{T}, v, inds...) where {T}
591
    @boundscheck checkbounds(a, inds...)
2,478✔
592
    li = _to_linear_index(a, inds...)
2,442✔
593
    ap = cconvert(Ptr{T}, a)
2,442✔
594
    p = unsafe_convert(Ptr{T}, ap) + sizeof(T) * (li - 1)
2,442✔
595
    GC.@preserve ap unsafe_store!(p, v)
2,442✔
596
    return a
2,442✔
597
end
598

599
@propagate_inbounds function _setindex_ra!(a::NonReshapedReinterpretArray{T,N,S}, v, i1::Int, tailinds::TT) where {T,N,S,TT}
600
    v = convert(T, v)::T
123,746,641✔
601
    # Make sure to match the scalar reinterpret if that is applicable
602
    if sizeof(T) == sizeof(S) && (fieldcount(T) + fieldcount(S)) == 0
123,746,539✔
603
        if issingletontype(T) # singleton types
123,746,167✔
604
            @boundscheck checkbounds(a, i1, tailinds...)
18✔
605
            # setindex! is a noop except for the index check
606
        else
607
            setindex!(a.parent, reinterpret(S, v), i1, tailinds...)
123,795,547✔
608
        end
609
    else
610
        @boundscheck checkbounds(a, i1, tailinds...)
426✔
611
        ind_start, sidx = divrem((i1-1)*sizeof(T), sizeof(S))
318✔
612
        # Optimizations that avoid branches
613
        if sizeof(T) % sizeof(S) == 0
318✔
614
            # T is bigger than S and contains an integer number of them
615
            t = Ref{T}(v)
57✔
616
            GC.@preserve t begin
57✔
617
                sptr = Ptr{S}(unsafe_convert(Ref{T}, t))
57✔
618
                n = sizeof(T) ÷ sizeof(S)
57✔
619
                for i = 1:n
57✔
620
                    s = unsafe_load(sptr, i)
75✔
621
                    a.parent[ind_start + i, tailinds...] = s
75✔
622
                end
93✔
623
            end
624
        elseif sizeof(S) % sizeof(T) == 0
261✔
625
            # S is bigger than T and contains an integer number of them
626
            s = Ref{S}(a.parent[ind_start + 1, tailinds...])
237✔
627
            GC.@preserve s begin
237✔
628
                tptr = Ptr{T}(unsafe_convert(Ref{S}, s))
237✔
629
                unsafe_store!(tptr + sidx, v)
237✔
630
                a.parent[ind_start + 1, tailinds...] = s[]
237✔
631
            end
632
        else
633
            t = Ref{T}(v)
24✔
634
            s = Ref{S}()
24✔
635
            GC.@preserve t s begin
24✔
636
                tptr = Ptr{UInt8}(unsafe_convert(Ref{T}, t))
24✔
637
                sptr = Ptr{UInt8}(unsafe_convert(Ref{S}, s))
24✔
638
                nbytes_copied = 0
24✔
639
                i = 1
24✔
640
                # Deal with any partial elements at the start. We'll have to copy in the
641
                # element from the original array and overwrite the relevant parts
642
                if sidx != 0
24✔
643
                    s[] = a.parent[ind_start + i, tailinds...]
15✔
644
                    nb = min((sizeof(S) - sidx) % UInt, sizeof(T) % UInt)
12✔
645
                    memcpy(sptr + sidx, tptr, nb)
12✔
646
                    nbytes_copied += nb
12✔
647
                    a.parent[ind_start + i, tailinds...] = s[]
12✔
648
                    i += 1
12✔
649
                    sidx = 0
12✔
650
                end
651
                # Deal with the main body of elements
652
                while nbytes_copied < sizeof(T) && (sizeof(T) - nbytes_copied) > sizeof(S)
36✔
653
                    nb = min(sizeof(S), sizeof(T) - nbytes_copied)
12✔
654
                    memcpy(sptr, tptr + nbytes_copied, nb)
12✔
655
                    nbytes_copied += nb
12✔
656
                    a.parent[ind_start + i, tailinds...] = s[]
12✔
657
                    i += 1
12✔
658
                end
12✔
659
                # Deal with trailing partial elements
660
                if nbytes_copied < sizeof(T)
24✔
661
                    s[] = a.parent[ind_start + i, tailinds...]
30✔
662
                    nb = min(sizeof(S), sizeof(T) - nbytes_copied)
24✔
663
                    memcpy(sptr, tptr + nbytes_copied, nb)
24✔
664
                    a.parent[ind_start + i, tailinds...] = s[]
24✔
665
                end
666
            end
667
        end
668
    end
669
    return a
123,746,509✔
670
end
671

672
@propagate_inbounds function _setindex_ra!(a::ReshapedReinterpretArray{T,N,S}, v, i1::Int, tailinds::TT) where {T,N,S,TT}
673
    v = convert(T, v)::T
267✔
674
    # Make sure to match the scalar reinterpret if that is applicable
675
    if sizeof(T) == sizeof(S) && (fieldcount(T) + fieldcount(S)) == 0
264✔
676
        if issingletontype(T) # singleton types
48✔
677
            @boundscheck checkbounds(a, i1, tailinds...)
9✔
678
            # setindex! is a noop except for the index check
679
        else
680
            setindex!(a.parent, reinterpret(S, v), i1, tailinds...)
42✔
681
        end
682
    end
683
    @boundscheck checkbounds(a, i1, tailinds...)
261✔
684
    if sizeof(T) >= sizeof(S)
261✔
685
        t = Ref{T}(v)
141✔
686
        GC.@preserve t begin
141✔
687
            sptr = Ptr{S}(unsafe_convert(Ref{T}, t))
141✔
688
            if sizeof(T) > sizeof(S)
141✔
689
                # Extra dimension in the parent array
690
                n = sizeof(T) ÷ sizeof(S)
81✔
691
                if isempty(tailinds) && IndexStyle(a.parent) === IndexLinear()
81✔
692
                    offset = n * (i1 - firstindex(a))
12✔
693
                    for i = 1:n
12✔
694
                        s = unsafe_load(sptr, i)
24✔
695
                        a.parent[i + offset] = s
24✔
696
                    end
36✔
697
                else
698
                    for i = 1:n
69✔
699
                        s = unsafe_load(sptr, i)
138✔
700
                        a.parent[i, i1, tailinds...] = s
138✔
701
                    end
207✔
702
                end
703
            else # sizeof(T) == sizeof(S)
704
                # No extra dimension
705
                s = unsafe_load(sptr)
60✔
706
                a.parent[i1, tailinds...] = s
141✔
707
            end
708
        end
709
    else
710
        # S is bigger than T and contains an integer number of them
711
        s = Ref{S}()
120✔
712
        GC.@preserve s begin
120✔
713
            tptr = Ptr{T}(unsafe_convert(Ref{S}, s))
120✔
714
            s[] = a.parent[tailinds...]
144✔
715
            unsafe_store!(tptr, v, i1)
120✔
716
            a.parent[tailinds...] = s[]
120✔
717
        end
718
    end
719
    return a
261✔
720
end
721

722
# Padding
723
struct Padding
724
    offset::Int # 0-indexed offset of the next valid byte; sizeof(T) indicates trailing padding
3✔
725
    size::Int   # bytes of padding before a valid byte
726
end
727
function intersect(p1::Padding, p2::Padding)
×
728
    start = max(p1.offset, p2.offset)
×
729
    stop = min(p1.offset + p1.size, p2.offset + p2.size)
×
730
    Padding(start, max(0, stop-start))
×
731
end
732

733
struct PaddingError <: Exception
734
    S::Type
12✔
735
    T::Type
736
end
737

738
function showerror(io::IO, p::PaddingError)
×
739
    print(io, "Padding of type $(p.S) is not compatible with type $(p.T).")
×
740
end
741

742
"""
743
    CyclePadding(padding, total_size)
744

745
Cycles an iterator of `Padding` structs, restarting the padding at `total_size`.
746
E.g. if `padding` is all the padding in a struct and `total_size` is the total
747
aligned size of that array, `CyclePadding` will correspond to the padding in an
748
infinite vector of such structs.
749
"""
750
struct CyclePadding{P}
751
    padding::P
16,090✔
752
    total_size::Int
753
end
754
eltype(::Type{<:CyclePadding}) = Padding
×
755
IteratorSize(::Type{<:CyclePadding}) = IsInfinite()
×
756
isempty(cp::CyclePadding) = isempty(cp.padding)
×
757
function iterate(cp::CyclePadding)
48✔
758
    y = iterate(cp.padding)
8,045✔
759
    y === nothing && return nothing
8,045✔
760
    y[1], (0, y[2])
×
761
end
762
function iterate(cp::CyclePadding, state::Tuple)
×
763
    y = iterate(cp.padding, tail(state)...)
×
764
    y === nothing && return iterate(cp, (state[1]+cp.total_size,))
×
765
    Padding(y[1].offset+state[1], y[1].size), (state[1], tail(y)...)
×
766
end
767

768
"""
769
    Compute the location of padding in an isbits datatype. Recursive over the fields of that type.
770
"""
771
@assume_effects :foldable function padding(T::DataType, baseoffset::Int = 0)
22,746✔
772
    pads = Padding[]
39,547✔
773
    last_end::Int = baseoffset
22,851✔
774
    for i = 1:fieldcount(T)
23,193✔
775
        offset = baseoffset + Int(fieldoffset(T, i))
2,079✔
776
        fT = fieldtype(T, i)
2,079✔
777
        append!(pads, padding(fT, offset))
2,079✔
778
        if offset != last_end
2,079✔
779
            push!(pads, Padding(offset, offset-last_end))
×
780
        end
781
        last_end = offset + sizeof(fT)
2,079✔
782
    end
3,809✔
783
    if 0 < last_end - baseoffset < sizeof(T)
22,851✔
784
        push!(pads, Padding(baseoffset + sizeof(T), sizeof(T) - last_end + baseoffset))
3✔
785
    end
786
    return Core.svec(pads...)
22,859✔
787
end
788

789
function CyclePadding(T::DataType)
16,090✔
790
    a, s = datatype_alignment(T), sizeof(T)
16,090✔
791
    as = s + (a - (s % a)) % a
16,090✔
792
    pad = padding(T)
16,090✔
793
    if s != as
16,090✔
794
        pad = Core.svec(pad..., Padding(s, as - s))
×
795
    end
796
    CyclePadding(pad, as)
16,090✔
797
end
798

799
@assume_effects :total function array_subpadding(S, T)
8,045✔
800
    lcm_size = lcm(sizeof(S), sizeof(T))
8,045✔
801
    s, t = CyclePadding(S), CyclePadding(T)
8,045✔
802
    checked_size = 0
8,045✔
803
    # use of Stateful harms inference and makes this vulnerable to invalidation
804
    (pad, tstate) = let
805
        it = iterate(t)
8,045✔
806
        it === nothing && return true
8,045✔
807
        it
×
808
    end
809
    (ps, sstate) = let
810
        it = iterate(s)
×
811
        it === nothing && return false
×
812
        it
×
813
    end
814
    while checked_size < lcm_size
×
815
        while true
×
816
            # See if there's corresponding padding in S
817
            ps.offset > pad.offset && return false
×
818
            intersect(ps, pad) == pad && break
×
819
            ps, sstate = iterate(s, sstate)
×
820
        end
×
821
        checked_size = pad.offset + pad.size
×
822
        pad, tstate = iterate(t, tstate)
×
823
    end
×
824
    return true
×
825
end
826

827
@assume_effects :foldable function struct_subpadding(::Type{Out}, ::Type{In}) where {Out, In}
143✔
828
    padding(Out) == padding(In)
143✔
829
end
830

831
@assume_effects :foldable function packedsize(::Type{T}) where T
237✔
832
    pads = padding(T)
237✔
833
    return sizeof(T) - sum((p.size for p ∈ pads), init = 0)
237✔
834
end
835

836
@assume_effects :foldable ispacked(::Type{T}) where T = isempty(padding(T))
48✔
837

838
function _copytopacked!(ptr_out::Ptr{Out}, ptr_in::Ptr{In}) where {Out, In}
9✔
839
    writeoffset = 0
12✔
840
    for i ∈ 1:fieldcount(In)
12✔
841
        readoffset = fieldoffset(In, i)
39✔
842
        fT = fieldtype(In, i)
39✔
843
        if ispacked(fT)
45✔
844
            readsize = sizeof(fT)
42✔
845
            memcpy(ptr_out + writeoffset, ptr_in + readoffset, readsize)
36✔
846
            writeoffset += readsize
36✔
847
        else # nested padded type
848
            _copytopacked!(ptr_out + writeoffset, Ptr{fT}(ptr_in + readoffset))
6✔
849
            writeoffset += packedsize(fT)
3✔
850
        end
851
    end
42✔
852
end
853

854
function _copyfrompacked!(ptr_out::Ptr{Out}, ptr_in::Ptr{In}) where {Out, In}
9✔
855
    readoffset = 0
12✔
856
    for i ∈ 1:fieldcount(Out)
12✔
857
        writeoffset = fieldoffset(Out, i)
39✔
858
        fT = fieldtype(Out, i)
39✔
859
        if ispacked(fT)
45✔
860
            writesize = sizeof(fT)
42✔
861
            memcpy(ptr_out + writeoffset, ptr_in + readoffset, writesize)
36✔
862
            readoffset += writesize
36✔
863
        else # nested padded type
864
            _copyfrompacked!(Ptr{fT}(ptr_out + writeoffset), ptr_in + readoffset)
6✔
865
            readoffset += packedsize(fT)
3✔
866
        end
867
    end
42✔
868
end
869

870
@inline function _reinterpret(::Type{Out}, x::In) where {Out, In}
871
    # handle non-primitive types
872
    isbitstype(Out) || throw(ArgumentError("Target type for `reinterpret` must be isbits"))
271✔
873
    isbitstype(In) || throw(ArgumentError("Source type for `reinterpret` must be isbits"))
268✔
874
    inpackedsize = packedsize(In)
265✔
875
    outpackedsize = packedsize(Out)
265✔
876
    inpackedsize == outpackedsize ||
265✔
877
        throw(ArgumentError(LazyString("Packed sizes of types ", Out, " and ", In,
878
            " do not match; got ", outpackedsize, " and ", inpackedsize, ", respectively.")))
879
    in = Ref{In}(x)
7,518✔
880
    out = Ref{Out}()
7,518✔
881
    if struct_subpadding(Out, In)
253✔
882
        # if packed the same, just copy
883
        GC.@preserve in out begin
7,509✔
884
            ptr_in = unsafe_convert(Ptr{In}, in)
7,509✔
885
            ptr_out = unsafe_convert(Ptr{Out}, out)
7,509✔
886
            memcpy(ptr_out, ptr_in, sizeof(Out))
7,509✔
887
        end
888
        return out[]
7,509✔
889
    else
890
        # mismatched padding
891
        return _reinterpret_padding(Out, x)
9✔
892
    end
893
end
894

895
# If the code reaches this part, it needs to handle padding and is unlikely
896
# to compile to a noop. Therefore, we don't forcibly inline it.
897
function _reinterpret_padding(::Type{Out}, x::In) where {Out, In}
898
    inpackedsize = packedsize(In)
9✔
899
    in = Ref{In}(x)
9✔
900
    out = Ref{Out}()
9✔
901
    GC.@preserve in out begin
9✔
902
        ptr_in = unsafe_convert(Ptr{In}, in)
9✔
903
        ptr_out = unsafe_convert(Ptr{Out}, out)
9✔
904

905
        if fieldcount(In) > 0 && ispacked(Out)
9✔
906
            _copytopacked!(ptr_out, ptr_in)
×
907
        elseif fieldcount(Out) > 0 && ispacked(In)
9✔
908
            _copyfrompacked!(ptr_out, ptr_in)
×
909
        else
910
            packed = Ref{NTuple{inpackedsize, UInt8}}()
9✔
911
            GC.@preserve packed begin
9✔
912
                ptr_packed = unsafe_convert(Ptr{NTuple{inpackedsize, UInt8}}, packed)
9✔
913
                _copytopacked!(ptr_packed, ptr_in)
9✔
914
                _copyfrompacked!(ptr_out, ptr_packed)
9✔
915
            end
916
        end
917
    end
918
    return out[]
9✔
919
end
920

921

922
# Reductions with IndexSCartesian2
923

924
function _mapreduce(f::F, op::OP, style::IndexSCartesian2{K}, A::AbstractArrayOrBroadcasted) where {F,OP,K}
925
    inds = eachindex(style, A)
12✔
926
    n = size(inds)[2]
12✔
927
    if n == 0
12✔
928
        return mapreduce_empty_iter(f, op, A, IteratorEltype(A))
×
929
    else
930
        return mapreduce_impl(f, op, A, first(inds), last(inds))
12✔
931
    end
932
end
933

934
@noinline function mapreduce_impl(f::F, op::OP, A::AbstractArrayOrBroadcasted,
24✔
935
                                  ifirst::SCI, ilast::SCI, blksize::Int) where {F,OP,SCI<:SCartesianIndex2{K}} where K
936
    if ilast.j - ifirst.j < blksize
24✔
937
        # sequential portion
938
        @inbounds a1 = A[ifirst]
18✔
939
        @inbounds a2 = A[SCI(2,ifirst.j)]
18✔
940
        v = op(f(a1), f(a2))
18✔
941
        @simd for i = ifirst.i + 2 : K
18✔
942
            @inbounds ai = A[SCI(i,ifirst.j)]
18✔
943
            v = op(v, f(ai))
18✔
944
        end
945
        # Remaining columns
946
        for j = ifirst.j+1 : ilast.j
18✔
947
            @simd for i = 1:K
7,998✔
948
                @inbounds ai = A[SCI(i,j)]
23,994✔
949
                v = op(v, f(ai))
23,994✔
950
            end
951
        end
15,978✔
952
        return v
18✔
953
    else
954
        # pairwise portion
955
        jmid = ifirst.j + (ilast.j - ifirst.j) >> 1
6✔
956
        v1 = mapreduce_impl(f, op, A, ifirst, SCI(K,jmid), blksize)
6✔
957
        v2 = mapreduce_impl(f, op, A, SCI(1,jmid+1), ilast, blksize)
6✔
958
        return op(v1, v2)
6✔
959
    end
960
end
961

962
mapreduce_impl(f::F, op::OP, A::AbstractArrayOrBroadcasted, ifirst::SCartesianIndex2, ilast::SCartesianIndex2) where {F,OP} =
12✔
963
    mapreduce_impl(f, op, A, ifirst, ilast, pairwise_blocksize(f, op))
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc