Skip to content

Commit

Permalink
Allow creating None enum flag with Enum.from_value
Browse files Browse the repository at this point in the history
  • Loading branch information
bew committed Aug 10, 2018
1 parent eeb53c5 commit c62e23a
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 9 deletions.
4 changes: 2 additions & 2 deletions spec/std/enum_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ describe Enum do
end

it "for flags enum" do
SpecEnumFlags.from_value?(0).should be_nil
SpecEnumFlags.from_value?(0).should eq(SpecEnumFlags::None)
SpecEnumFlags.from_value?(1).should eq(SpecEnumFlags::One)
SpecEnumFlags.from_value?(2).should eq(SpecEnumFlags::Two)
SpecEnumFlags.from_value?(3).should eq(SpecEnumFlags::One | SpecEnumFlags::Two)
Expand All @@ -134,10 +134,10 @@ describe Enum do
end

it "for flags enum" do
expect_raises(Exception, "Unknown enum SpecEnumFlags value: 0") { SpecEnumFlags.from_value(0) }
SpecEnumFlags.from_value(1).should eq(SpecEnumFlags::One)
SpecEnumFlags.from_value(2).should eq(SpecEnumFlags::Two)
SpecEnumFlags.from_value(3).should eq(SpecEnumFlags::One | SpecEnumFlags::Two)
expect_raises(Exception, "Unknown enum SpecEnumFlags value: 8") { SpecEnumFlags.from_value(8) }
end
end

Expand Down
2 changes: 1 addition & 1 deletion src/debug/elf.cr
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ module Debug
ei_version = @io.read_byte.not_nil!
raise Error.new("Unsupported version number") unless ei_version == 1

ei_osabi = OSABI.from_value(@io.read_byte)
ei_osabi = OSABI.from_value(@io.read_byte.not_nil!)
ei_abiversion = @io.read_byte.not_nil!

# padding (unused)
Expand Down
10 changes: 4 additions & 6 deletions src/enum.cr
Original file line number Diff line number Diff line change
Expand Up @@ -337,12 +337,10 @@ struct Enum
# Color.from_value?(2) # => Color::Blue
# Color.from_value?(3) # => nil
# ```
def self.from_value?(value) : self?
def self.from_value?(value : Int) : self?
{% if @type.has_attribute?("Flags") %}
mask = {% for member, i in @type.constants %}\
{% if i != 0 %} | {% end %}\
{{@type}}::{{member}}.value{% end %}
return if (mask & value != value) || (value == 0 && values.none? { |val| val.to_i == 0 })
all_mask = {{@type}}::All.value
return if all_mask & value != value
return new(value)
{% else %}
{% for member in @type.constants %}
Expand All @@ -361,7 +359,7 @@ struct Enum
# Color.from_value(2) # => Color::Blue
# Color.from_value(3) # raises Exception
# ```
def self.from_value(value) : self
def self.from_value(value : Int) : self
from_value?(value) || raise "Unknown enum #{self} value: #{value}"
end

Expand Down

0 comments on commit c62e23a

Please sign in to comment.