Skip to content

Commit

Permalink
feat: cache is_unspecified for zeroconf ip address objects (#1331)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco committed Dec 13, 2023
1 parent ede0a2a commit a1c84dc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/zeroconf/_utils/ipaddress.py
Expand Up @@ -34,13 +34,14 @@

class ZeroconfIPv4Address(IPv4Address):

__slots__ = ("_str", "_is_link_local")
__slots__ = ("_str", "_is_link_local", "_is_unspecified")

def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize a new IPv4 address."""
super().__init__(*args, **kwargs)
self._str = super().__str__()
self._is_link_local = super().is_link_local
self._is_unspecified = super().is_unspecified

def __str__(self) -> str:
"""Return the string representation of the IPv4 address."""
Expand All @@ -51,16 +52,22 @@ def is_link_local(self) -> bool:
"""Return True if this is a link-local address."""
return self._is_link_local

@property
def is_unspecified(self) -> bool:
"""Return True if this is an unspecified address."""
return self._is_unspecified


class ZeroconfIPv6Address(IPv6Address):

__slots__ = ("_str", "_is_link_local")
__slots__ = ("_str", "_is_link_local", "_is_unspecified")

def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize a new IPv6 address."""
super().__init__(*args, **kwargs)
self._str = super().__str__()
self._is_link_local = super().is_link_local
self._is_unspecified = super().is_unspecified

def __str__(self) -> str:
"""Return the string representation of the IPv6 address."""
Expand All @@ -71,6 +78,11 @@ def is_link_local(self) -> bool:
"""Return True if this is a link-local address."""
return self._is_link_local

@property
def is_unspecified(self) -> bool:
"""Return True if this is an unspecified address."""
return self._is_unspecified


@lru_cache(maxsize=512)
def _cached_ip_addresses(address: Union[str, bytes, int]) -> Optional[Union[IPv4Address, IPv6Address]]:
Expand Down
12 changes: 12 additions & 0 deletions tests/utils/test_ipaddress.py
Expand Up @@ -18,7 +18,19 @@ def test_cached_ip_addresses_wrapper():
ipv4 = ipaddress.cached_ip_addresses('169.254.0.0')
assert ipv4 is not None
assert ipv4.is_link_local is True
assert ipv4.is_unspecified is False

ipv4 = ipaddress.cached_ip_addresses('0.0.0.0')
assert ipv4 is not None
assert ipv4.is_link_local is False
assert ipv4.is_unspecified is True

ipv6 = ipaddress.cached_ip_addresses('fe80::1')
assert ipv6 is not None
assert ipv6.is_link_local is True
assert ipv6.is_unspecified is False

ipv6 = ipaddress.cached_ip_addresses('0:0:0:0:0:0:0:0')
assert ipv6 is not None
assert ipv6.is_link_local is False
assert ipv6.is_unspecified is True

0 comments on commit a1c84dc

Please sign in to comment.