enums v1.2 library / gem adds (enum) flags w/ bitwise-operators for set (|) / unset (&~) / toggle (^)

(Gerald Bauer) #1

Hello,

I've added (bit) enum flags with bitwise-operators
for set (|) / unset (&~) / toggle (^) to the enums library / gem [1].

Use the new flags option for the enum helper or the new Flag class. Example:

 Flag.new( :FileAttrib, :read_only, :hidden, :system, :archive )
 # -or -
 enum :FileAttrib, [:read_only, :hidden, :system, :archive], flags: true
 # -or -
 enum :FileAttrib, :read_only, :hidden, :system, :archive, flags: true
 # -or -
 enum :FileAttrib, { read_only: 1<<0,    # 2^0 = 1  = 0b00000001
                     hidden:    1<<1,    # 2^1 = 2  = 0b00000010
                     system:    1<<2,    # 2^2 = 4  = 0b00000100
                     archive:   1<<5,    # 2^5 = 32 = 0b00100000
                   },
                   flags: true

and use like:

FileAttrib.values  #=> [1, 2, 4, 8]
FileAttrib.keys    #=> [:read_only, :hidden, :system, :archive]

FileAttrib.read_only                      #=> <FileAttrib
@key=:read_only, @value=1>
FileAttrib::READ_ONLY                     #=> <FileAttrib
@key=:read_only, @value=1>
FileAttribs[:read_only]                    #=> <FileAttrib
@key=:read_only, @value=1>

FileAttrib(0)                             #=> <FileAttrib @key=:0000, @value=0>
FileAttrib.read_only | FileAttrib.hidden  #=> <FileAttrib @key=:0011, @value=3>
# -or-
FileAttrib.new( FileAttrib.read_only | FileAttrib.hidden )
FileAttrib.new( FileAttrib::READ_ONLY | FileAttrib::HIDDEN )
FileAttrib.new( :read_only, :hidden )
# -or-
FileAttrib( FileAttrib.read_only | FileAttrib.hidden )
FileAttrib( FileAttrib::READ_ONLY | FileAttrib::HIDDEN )
FileAttrib( :read_only, :hidden )
#=> <FileAttrib @key=:0011, @value=3>

attrib  = FileAttrib.new        #=> <FileAttrib @key=:0000, @value=0>
attrib |= FileAttrib.read_only  #=> <FileAttrib @key=:0001, @value=1>
attrib.read_only?               #=> true
# -or-
attrib.member?( FileAttrib.read_only )                #=> true
attrib.member?( FileAttrib.READ_ONLY )                #=> true
attrib.member?( :read_only )                          #=> true
attrib & FileAttrib.read_only == FileAttrib.read_only #=> true

attrib ^= FileAttrib.read_only  #=> <FileAttrib @key=:0000, @value=0>
attrib.read_only?               #=> false
attrib ^= FileAttrib.read_only  #=> <FileAttrib @key=:0001, @value=1>
attrib.read_only?               #=> true

attrib &= ~FileAttrib.read_only #=> <FileAttrib @key=:0000, @value=0>
attrib.read_only?               #=> false

attrib.is_a? Flag               #=> true
attrib.is_a? FileAttrib         #=> true
# ...

and so on.

Happy enumerating or bit flagging or masking with (secure) ruby.

PS: Note: The enums library / gem is part of the safe data structure
(safestruct) series. [2]

[1] https://github.com/s6ruby/enums#what-about-enums-with-flags-and-bitwise-operators-for-set---unset---toggle-
[2] https://github.com/s6ruby/safestruct

0 Likes