Skip to content

Commit

Permalink
Merge pull request #47 from skipkayhil/optimize-include
Browse files Browse the repository at this point in the history
Improve performance of include? by 5-10x
  • Loading branch information
knu committed Sep 23, 2023
2 parents 1dfa2a8 + b8d0323 commit 1081c2e
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions lib/ipaddr.rb
Expand Up @@ -176,9 +176,7 @@ def mask(prefixlen)
def include?(other)
other = coerce_other(other)
return false unless other.family == family
range = to_range
other = other.to_range
range.begin <= other.begin && range.end >= other.end
begin_addr <= other.begin_addr && end_addr >= other.end_addr
end
alias === include?

Expand Down Expand Up @@ -406,17 +404,6 @@ def hash

# Creates a Range object for the network address.
def to_range
begin_addr = (@addr & @mask_addr)

case @family
when Socket::AF_INET
end_addr = (@addr | (IN4MASK ^ @mask_addr))
when Socket::AF_INET6
end_addr = (@addr | (IN6MASK ^ @mask_addr))
else
raise AddressFamilyError, "unsupported address family"
end

self.class.new(begin_addr, @family)..self.class.new(end_addr, @family)
end

Expand Down Expand Up @@ -497,6 +484,21 @@ def zone_id=(zid)

protected

def begin_addr
@addr & @mask_addr
end

def end_addr
case @family
when Socket::AF_INET
@addr | (IN4MASK ^ @mask_addr)
when Socket::AF_INET6
@addr | (IN6MASK ^ @mask_addr)
else
raise AddressFamilyError, "unsupported address family"
end
end

# Set +@addr+, the internal stored ip address, to given +addr+. The
# parameter +addr+ is validated using the first +family+ member,
# which is +Socket::AF_INET+ or +Socket::AF_INET6+.
Expand Down

0 comments on commit 1081c2e

Please sign in to comment.