Skip to content
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

Raise when calling #size on an open range #8829

Merged
merged 1 commit into from
Feb 21, 2020
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
12 changes: 12 additions & 0 deletions spec/std/range_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,18 @@ describe "Range" do
it "works for other types" do
('a'..'c').size.should eq(3)
end

it "raises on beginless range" do
expect_raises(ArgumentError, "Can't calculate size of an open range") do
((true ? nil : 1)..3).size
Sija marked this conversation as resolved.
Show resolved Hide resolved
end
end

it "raises on endless range" do
expect_raises(ArgumentError, "Can't calculate size of an open range") do
(3..(true ? nil : 1)).size
end
end
end

it "clones" do
Expand Down
7 changes: 7 additions & 0 deletions src/range.cr
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,10 @@ struct Range(B, E)

# :nodoc:
def size
{% if B == Nil || E == Nil %}
{% raise "Can't calculate size of an open range" %}
{% end %}

b = self.begin
e = self.end

Expand All @@ -355,6 +359,9 @@ struct Range(B, E)
n = e - b + 1
n < 0 ? 0 : n
else
if b.nil? || e.nil?
raise ArgumentError.new("Can't calculate size of an open range")
end
super
end
end
Expand Down