/lib/dnssd/flags.rb

https://github.com/peddie/dnssd · Ruby · 116 lines · 59 code · 33 blank · 24 comment · 4 complexity · c895f4daca726f2f2e5d38d7f626bbb6 MD5 · raw file

  1. ##
  2. # Flags used in DNSSD Ruby API.
  3. class DNSSD::Flags
  4. constants.each do |name|
  5. next unless name =~ /[a-z]/
  6. attr = name.to_s.gsub(/([a-z])([A-Z])/, '\1_\2').downcase
  7. flag = const_get name
  8. define_method "#{attr}=" do |bool|
  9. if bool then
  10. set_flag flag
  11. else
  12. clear_flag flag
  13. end
  14. end
  15. define_method "#{attr}?" do
  16. self & flag == flag
  17. end
  18. end
  19. ##
  20. # Bitfield with all valid flags set
  21. ALL_FLAGS = FLAGS.values.inject { |flag, all| flag | all }
  22. ##
  23. # Returns a new set of flags
  24. def initialize(*flags)
  25. @flags = flags.inject 0 do |flag, acc| flag | acc end
  26. verify
  27. end
  28. ##
  29. # Returns the intersection of flags in +self+ and +flags+.
  30. def &(flags)
  31. self.class.new(to_i & flags.to_i)
  32. end
  33. ##
  34. # +self+ is equal if +other+ has the same flags
  35. def ==(other)
  36. to_i == other.to_i
  37. end
  38. ##
  39. # Clears +flag+
  40. def clear_flag(flag)
  41. @flags &= ~flag
  42. verify
  43. end
  44. def inspect # :nodoc:
  45. flags = to_a.sort.join ', '
  46. flags[0, 0] = ' ' unless flags.empty?
  47. "#<#{self.class}#{flags}>"
  48. end
  49. ##
  50. # Sets +flag+
  51. def set_flag(flag)
  52. @flags |= flag
  53. verify
  54. end
  55. ##
  56. # Returns an Array of flag names
  57. def to_a
  58. FLAGS.map do |name, value|
  59. (@flags & value == value) ? name : nil
  60. end.compact
  61. end
  62. ##
  63. # Flags as a bitfield
  64. def to_i
  65. @flags
  66. end
  67. ##
  68. # Trims the flag list down to valid flags
  69. def verify
  70. @flags &= ALL_FLAGS
  71. self
  72. end
  73. ##
  74. # Returns the union of flags in +self+ and +flags+
  75. def |(flags)
  76. self.class.new(to_i | flags.to_i)
  77. end
  78. ##
  79. # Returns the complement of the flags in +self+
  80. def ~
  81. self.class.new ~to_i
  82. end
  83. end