Skip to content

Commit 311cacc

Browse files
committed
invperm: check if arg is a permutation
1 parent 20a66de commit 311cacc

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

src/StaticArrays.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import Base: getindex, setindex!, size, similar, vec, show, length, convert, pro
66
promote_rule, map, map!, reduce, mapreduce, foldl, mapfoldl, broadcast,
77
broadcast!, conj, hcat, vcat, ones, zeros, one, reshape, fill, fill!, inv,
88
iszero, sum, prod, count, any, all, minimum, maximum, extrema,
9-
copy, read, read!, write, reverse
9+
copy, read, read!, write, reverse, invperm
1010

1111
using Random
1212
import Random: rand, randn, randexp, rand!, randn!, randexp!

src/util.jl

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,12 @@ TrivialView(a::AbstractArray{T,N}) where {T,N} = TrivialView{typeof(a),T,N}(a)
7474
@inline drop_sdims(a::StaticArrayLike) = TrivialView(a)
7575
@inline drop_sdims(a) = a
7676

77-
Base.@propagate_inbounds function invperm(p::StaticVector)
78-
# in difference to base, this does not check if p is a permutation (every value unique)
79-
ip = similar(p)
80-
ip[p] = 1:length(p)
81-
similar_type(p)(ip)
77+
@inline function invperm(p::StaticVector{N,T}) where {N,T<:Integer}
78+
ip = zeros(MVector{N,T})
79+
@inbounds for i in SOneTo(N)
80+
j = p[i]
81+
1 <= j <= N && iszero(ip[j]) || throw(ArgumentError("argument is not a permutation"))
82+
ip[j] = i
83+
end
84+
SVector(ip)
8285
end
83-

0 commit comments

Comments
 (0)