Skip to content

Commit 7f02104

Browse files
blegatodow
andauthored
Add docstring to _reinterpret_unsafe (#2745)
Co-authored-by: odow <o.dowson@gmail.com>
1 parent 103fe75 commit 7f02104

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/Nonlinear/ReverseAD/utils.jl

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,43 @@ function _UnsafeLowerTriangularMatrixView(x::Vector{Float64}, N::Int)
164164
return _UnsafeLowerTriangularMatrixView(N, pointer(x))
165165
end
166166

167+
"""
168+
_reinterpret_unsafe(::Type{T}, x::Vector{R}) where {T,R}
169+
170+
Return an `_UnsafeVectorView` that act as a vector of element type
171+
`T` over the same bytes as `x`. Note that if `length(x) * sizeof(R)` is not
172+
a multiple of `sizeof(T)`, the last bits will be ignored. This is a key
173+
difference with `reinterpret` which errors in that case.
174+
175+
Given a vector of `Float64` of length equal to the maximum number of nodes of a
176+
set of expressions time the maximum chunk size, this function is used to
177+
reinterpret it as a vector of `ForwardDiff.Partials{N,T}` where `N` is the
178+
chunk size of one of the expressions of the set. In that case, we know that
179+
the vector has enough bytes and we don't care about the leftover bytes at the
180+
end.
181+
182+
## Examples
183+
184+
```jldoctest
185+
julia> import MathOptInterface as MOI
186+
187+
julia> x = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
188+
3-element Vector{Tuple{Int64, Int64, Int64}}:
189+
(1, 2, 3)
190+
(4, 5, 6)
191+
(7, 8, 9)
192+
193+
julia> MOI.Nonlinear.ReverseAD._reinterpret_unsafe(NTuple{2,Int}, x)
194+
4-element MathOptInterface.Nonlinear.ReverseAD._UnsafeVectorView{Tuple{Int64, Int64}}:
195+
(1, 2)
196+
(3, 4)
197+
(5, 6)
198+
(7, 8)
199+
```
200+
"""
167201
function _reinterpret_unsafe(::Type{T}, x::Vector{R}) where {T,R}
168-
# how many T's fit into x?
169202
@assert isbitstype(T) && isbitstype(R)
203+
# how many T's fit into x?
170204
len = length(x) * sizeof(R)
171205
p = reinterpret(Ptr{T}, pointer(x))
172206
return _UnsafeVectorView(0, div(len, sizeof(T)), p)

0 commit comments

Comments
 (0)