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

Fix Enum#includes? to require all bits set #13229

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions spec/std/enum_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,12 @@ describe Enum do
it "does includes?" do
(SpecEnumFlags::One | SpecEnumFlags::Two).includes?(SpecEnumFlags::One).should be_true
(SpecEnumFlags::One | SpecEnumFlags::Two).includes?(SpecEnumFlags::Three).should be_false
SpecEnumFlags::One.includes?(SpecEnumFlags::None).should be_true
SpecEnumFlags::None.includes?(SpecEnumFlags::None).should be_true
SpecEnumFlags::None.includes?(SpecEnumFlags::One).should be_false
SpecEnumFlags::One.includes?(SpecEnumFlags::One | SpecEnumFlags::Two).should be_false
(SpecEnumFlags::One | SpecEnumFlags::Two).includes?(SpecEnumFlags::One | SpecEnumFlags::Two).should be_true
(SpecEnumFlags::One | SpecEnumFlags::Two | SpecEnumFlags::Three).includes?(SpecEnumFlags::One | SpecEnumFlags::Two).should be_true
end

describe "each" do
Expand Down
19 changes: 4 additions & 15 deletions src/enum.cr
Original file line number Diff line number Diff line change
Expand Up @@ -337,20 +337,9 @@ struct Enum
end

# Returns `true` if this enum member's value includes *other*. This
# performs a logical "and" between this enum member's value and *other*'s,
# so instead of writing:
# performs a logical "and" between this enum member's value and *other*'s.
#
# ```
# (member & value) != 0
# ```
#
# you can write:
#
# ```
# member.includes?(value)
# ```
#
# The above is mostly useful with flag enums.
# This is mostly useful for flag enums.
#
# For example:
#
Expand All @@ -360,7 +349,7 @@ struct Enum
# mode.includes?(IOMode::Async) # => false
# ```
def includes?(other : self) : Bool
(value & other.value) != 0
value.bits_set?(other.value)
end

# Returns `true` if this enum member and *other* have the same underlying value.
Expand Down Expand Up @@ -390,7 +379,7 @@ struct Enum
{% if @type.annotation(Flags) %}
return if value == 0
{% for member in @type.constants %}
{% if member.stringify != "All" %}
{% if member.stringify != "All" && member.stringify != "None" %}
straight-shoota marked this conversation as resolved.
Show resolved Hide resolved
if includes?(self.class.new({{@type.constant(member)}}))
yield self.class.new({{@type.constant(member)}}), {{@type.constant(member)}}
end
Expand Down