Created
March 22, 2017 08:47
-
-
Save elomatreb/b1e0a7d58ada4147c7bbcbc994efc0f0 to your computer and use it in GitHub Desktop.
Ruby utility for parsing bitmask options.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# Bitmask[:list, :of, :option, :keys, value] | |
# where the last key in the list will be represented by the least significant | |
# bit in value. | |
# | |
# Example: | |
# Bitmask[:optionA, nil, :optionB, :optionC, 0b1010] | |
# #=> {:optionA=>true, :optionB=>true, :optionC=>false} | |
# Use nils to indicate bits that do not have a meaning. | |
class Bitmask | |
def self.[](*fields, bitmask) | |
unless bitmask.is_a? Integer | |
raise ArgumentError, | |
"A bitmask can only be an Integer, #{bitmask.class} given" | |
end | |
Hash[ | |
fields.map.with_index(1) do |field, bit| | |
next unless field | |
[field, bitmask & (1 << fields.size - bit) > 0] | |
end.compact | |
] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment