diff --git a/lib/ctypes/bitfield.rb b/lib/ctypes/bitfield.rb index 0e5ad03..a58cee7 100644 --- a/lib/ctypes/bitfield.rb +++ b/lib/ctypes/bitfield.rb @@ -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 diff --git a/lib/ctypes/enum.rb b/lib/ctypes/enum.rb index 0d2a78c..83bb105 100644 --- a/lib/ctypes/enum.rb +++ b/lib/ctypes/enum.rb @@ -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 diff --git a/lib/ctypes/helpers.rb b/lib/ctypes/helpers.rb index cbf9913..cf77d59 100644 --- a/lib/ctypes/helpers.rb +++ b/lib/ctypes/helpers.rb @@ -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 diff --git a/lib/ctypes/version.rb b/lib/ctypes/version.rb index cdc962d..618a9c1 100644 --- a/lib/ctypes/version.rb +++ b/lib/ctypes/version.rb @@ -4,5 +4,5 @@ # SPDX-License-Identifier: MIT module CTypes - VERSION = "0.2.3" + VERSION = "0.3.0" end diff --git a/spec/ctypes/enum_spec.rb b/spec/ctypes/enum_spec.rb index bed9e5f..a280efa 100644 --- a/spec/ctypes/enum_spec.rb +++ b/spec/ctypes/enum_spec.rb @@ -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 @@ -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