Skip to content

Commit

Permalink
Add Int#bits_set? method (#5619)
Browse files Browse the repository at this point in the history
  • Loading branch information
RX14 committed Jan 21, 2018
1 parent e83e894 commit e5da7d3
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/colorize.cr
Expand Up @@ -318,7 +318,7 @@ struct Colorize::Object(T)
unless mode_is_default
# Can't reuse MODES constant because it has bold/bright duplicated
{% for name in %w(bold dim underline blink reverse hidden) %}
if (@mode & MODE_{{name.upcase.id}}_FLAG) != 0
if @mode.bits_set? MODE_{{name.upcase.id}}_FLAG
io << ";" if printed
io << MODE_{{name.upcase.id}}
printed = true
Expand Down
5 changes: 3 additions & 2 deletions src/crystal/system/unix/file_descriptor.cr
Expand Up @@ -27,7 +27,8 @@ module Crystal::System::FileDescriptor
end

private def system_blocking?
fcntl(LibC::F_GETFL) & LibC::O_NONBLOCK == 0
flags = fcntl(LibC::F_GETFL)
!flags.bits_set? LibC::O_NONBLOCK
end

private def system_blocking=(value)
Expand All @@ -43,7 +44,7 @@ module Crystal::System::FileDescriptor

private def system_close_on_exec?
flags = fcntl(LibC::F_GETFD)
(flags & LibC::FD_CLOEXEC) == LibC::FD_CLOEXEC
flags.bits_set? LibC::FD_CLOEXEC
end

private def system_close_on_exec=(arg : Bool)
Expand Down
6 changes: 3 additions & 3 deletions src/debug/mach_o.cr
Expand Up @@ -117,7 +117,7 @@ module Debug
end

def abi64?
cputype.value & ABI64 == ABI64
cputype.value.bits_set? ABI64
end

def endianness
Expand Down Expand Up @@ -292,11 +292,11 @@ module Debug
end

def pext?
(value & PEXT) == PEXT
value.bits_set? PEXT
end

def ext?
(value & EXT) == EXT
value.bits_set? EXT
end

{% for flag in %w(UNDF ABS SECT PBUD INDR) %}
Expand Down
2 changes: 1 addition & 1 deletion src/enum.cr
Expand Up @@ -100,7 +100,7 @@ struct Enum
found = false
{% for member in @type.constants %}
{% if member.stringify != "All" %}
if {{@type}}::{{member}}.value != 0 && (value & {{@type}}::{{member}}.value) == {{@type}}::{{member}}.value
if {{@type}}::{{member}}.value != 0 && value.bits_set? {{@type}}::{{member}}.value
io << " | " if found
io << {{member.stringify}}
found = true
Expand Down
11 changes: 11 additions & 0 deletions src/int.cr
Expand Up @@ -296,6 +296,17 @@ struct Int
self >> bit & 1
end

# Returns `true` if all bits in *mask* are set on `self`.
#
# ```
# 0b0110.bits_set?(0b0110) # => true
# 0b1101.bits_set?(0b0111) # => false
# 0b1101.bits_set?(0b1100) # => true
# ```
def bits_set?(mask)
(self & mask) == mask
end

def gcd(other : Int)
self == 0 ? other.abs : (other % self).gcd(self)
end
Expand Down

0 comments on commit e5da7d3

Please sign in to comment.