Skip to content

Commit a05852b

Browse files
authored
Merge pull request #18830 from JuliaLang/jb/sortovf
fix integer overflow issue in counting sort, PR #18791
2 parents 2adf0a6 + c28148e commit a05852b

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

base/sort.jl

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
module Sort
44

5-
using Base: Order, copymutable, linearindices, linearindexing, viewindexing, LinearFast
5+
using Base: Order, Checked, copymutable, linearindices, linearindexing, viewindexing, LinearFast
66

77
import
88
Base.sort,
@@ -435,8 +435,9 @@ function sort!(v::AbstractVector;
435435
n = length(v)
436436
if n > 1
437437
min, max = extrema(v)
438-
rangelen = max - min + 1
439-
if rangelen < div(n,2)
438+
(diff, o1) = sub_with_overflow(max, min)
439+
(rangelen, o2) = add_with_overflow(diff, one(diff))
440+
if !o1 && !o2 && rangelen < div(n,2)
440441
return sort_int_range!(v, rangelen, min)
441442
end
442443
end
@@ -523,8 +524,9 @@ function sortperm(v::AbstractVector;
523524
n = length(v)
524525
if n > 1
525526
min, max = extrema(v)
526-
rangelen = max - min + 1
527-
if rangelen < div(n,2)
527+
(diff, o1) = sub_with_overflow(max, min)
528+
(rangelen, o2) = add_with_overflow(diff, one(diff))
529+
if !o1 && !o2 && rangelen < div(n,2)
528530
return sortperm_int_range(v, rangelen, min)
529531
end
530532
end

test/sorting.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,3 +348,7 @@ end
348348

349349
# issue #12833 - type stability of sort
350350
@test Base.return_types(sort, (Vector{Int},)) == [Vector{Int}]
351+
352+
# PR #18791
353+
@test sort([typemax(Int),typemin(Int)]) == [typemin(Int),typemax(Int)]
354+
@test sort([typemax(UInt),0]) == [0,typemax(UInt)]

0 commit comments

Comments
 (0)