Skip to content

Preserve type in first for OneTo #56263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,11 @@ first(r::OneTo{T}) where {T} = oneunit(T)
first(r::StepRangeLen) = unsafe_getindex(r, 1)
first(r::LinRange) = r.start

function first(r::OneTo, n::Integer)
n < 0 && throw(ArgumentError("Number of elements must be non-negative"))
OneTo(oftype(r.stop, min(r.stop, n)))
end

last(r::OrdinalRange{T}) where {T} = convert(T, r.stop) # via steprange_last
last(r::StepRangeLen) = unsafe_getindex(r, length(r))
last(r::LinRange) = r.stop
Expand Down
6 changes: 6 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1539,6 +1539,9 @@ end
@test size(r) == (3,)
@test step(r) == 1
@test first(r) == 1
@test first(r,2) === Base.OneTo(2)
@test first(r,20) === r
@test_throws ArgumentError first(r,-20)
@test last(r) == 3
@test minimum(r) == 1
@test maximum(r) == 3
Expand Down Expand Up @@ -1570,6 +1573,9 @@ end
@test findall(in(2:(length(r) - 1)), r) === 2:(length(r) - 1)
@test findall(in(r), 2:(length(r) - 1)) === 1:(length(r) - 2)
end
let r = Base.OneTo(Int8(4))
@test first(r,4) === r
end
@test convert(Base.OneTo, 1:2) === Base.OneTo{Int}(2)
@test_throws ArgumentError("first element must be 1, got 2") convert(Base.OneTo, 2:3)
@test_throws ArgumentError("step must be 1, got 2") convert(Base.OneTo, 1:2:5)
Expand Down