Skip to content
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
2 changes: 1 addition & 1 deletion lib/ctypes/bitfield.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def self.apply_layout(builder)

# get the size of the bitfield in bytes
def self.size
@type.size
@type&.size
end

# check if bitfield is a fixed size
Expand Down
19 changes: 15 additions & 4 deletions lib/ctypes/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -185,15 +185,26 @@ def permissive
Enum.new(@type, @dry_type.mapping, permissive: true)
end

# lookup the key for a given Integer value in this Enum
# Convert a enum key to value, or value to key
# @param arg [Integer, Symbol] key or value
# @return [Symbol, Integer, nil] value or key if known, nil if unknown
#
# @example
# e = Enum.new(%i[a b c])
# e[1] # => :b
# e[5] # => nil
def [](value)
@inverted_mapping ||= @dry_type.mapping.invert
@inverted_mapping[value]
# e[:b] # => 1
# e[:x] # => nil
def [](arg)
case arg
when Integer
@inverted_mapping ||= @dry_type.mapping.invert
@inverted_mapping[arg]
when Symbol
@dry_type.mapping[arg]
else
raise ArgumentError, "arg must be Integer or Symbol: %p" % [arg]
end
end
end
end
Expand Down
6 changes: 6 additions & 0 deletions lib/ctypes/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,10 @@ def bitfield(type = nil, bits = nil, &block)
end
end
end

# To make CTypes easier to use without including Helpers everywhere, we're
# going to extend Helpers into the CTypes namespace. This is to support
# interactive sessions through pry/irb where you need to quickly create types
# without having to constantly type out `Helpers`.
CTypes.extend(Helpers)
end
2 changes: 1 addition & 1 deletion lib/ctypes/version.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
# SPDX-License-Identifier: MIT

module CTypes
VERSION = "0.2.3"
VERSION = "0.3.0"
end
12 changes: 11 additions & 1 deletion spec/ctypes/enum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@
end

context "#[]" do
it "will return the Symbol for a valid value" do
it "will return the Symbol for a known value" do
e = described_class.new(%i[a b c])
expect(e[1]).to eq(:b)
end
Expand All @@ -129,5 +129,15 @@
e = described_class.new(%i[a b c])
expect(e[100]).to be_nil
end

it "will return the value for a known Symbol" do
e = described_class.new({x: 0x1000})
expect(e[:x]).to eq(0x1000)
end

it "will return nil for an unknown Symbol" do
e = described_class.new(%i[a b c])
expect(e[:unknown]).to be_nil
end
end
end
Loading