Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of include? by 5-10x #47

Merged
merged 1 commit into from
Sep 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions lib/ipaddr.rb
Original file line number Diff line number Diff line change
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 @@ -400,17 +398,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 @@ -491,6 +478,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