o inhg@sddZddlZddlmZmZmZmZmZm Z ddl m Z m Z m Z ddZddZGd d d eZdS) z2Set based operations for IP addresses and subnets.N) IPNetwork IPAddressIPRange cidr_merge cidr_excludeiprange_to_cidrs) _sys_maxint _dict_keys _int_typec Cs|jj}||}|j|jkr|||j|jdf|d7}|}|t|krR||}||vr/n#|jd|jkr8n|||jd|jdf|d7}|}|t|ks&|jd}|j} || krf|||| f|S)aCalculate IPSet([supernet]) - IPSet(subnets). Assumptions: subnets is sorted, subnet_idx points to the first element in subnets that is a subnet of supernet. Results are appended to the ranges parameter as tuples of in format (version, first, last). Return value is the first subnet_idx that does not point to a subnet of supernet (or len(subnets) if all subsequents items are a subnet of supernet). )_moduleversionfirstappendlenlast) supernetsubnets subnet_idxrangesr subnet prev_subnet cur_subnetrrr:/usr/local/lib/python3.10/dist-packages/netaddr/ip/sets.py _subtracts*    rccs|sdS|d\}}}|ddD]#\}}}||dkr$||kr$|}qt||t||fV|}|}|}qt||t||fVdS)aqIterate over sorted_ranges, merging where possible Sorted ranges must be a sorted iterable of (version, first, last) tuples. Merging occurs for pairs like [(4, 10, 42), (4, 43, 100)] which is merged into (4, 10, 100), and leads to return value ( IPAddress(10, 4), IPAddress(100, 4) ), which is suitable input for the iprange_to_cidrs function. Nrr )r) sorted_rangescurrent_version current_start current_stop next_version next_start next_stoprrr_iter_merged_ranges8s"  r#c@sHeZdZdZdZdGddZddZd d Zd d Zd dZ ddZ ddZ ddZ e Z ddZddZdHddZdHddZddZdd Zd!d"ZdHd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZeZd/d0Zd1d2ZeZd3d4ZeZ d5d6Z!e!Z"d7d8Z#e#Z$d9d:Z%e%Z&d;d<Z'e(d=d>Z)d?d@Z*e*Z+dAdBZ,dCdDZ-dEdFZ.dS)IIPSetz[ Represents an unordered collection (set) of unique IP addresses and subnets. )_cidrs __weakref__NrcCst|tr |jdi|_dSt|tr"tt|d|dd|_dSt|tr2t| d|_dSi|_|dur\g}|D]}t|t rJt ||d}| |q=t |D] }d|j|<qTdSdS)aL Constructor. :param iterable: (optional) an iterable containing IP addresses, subnets or ranges. :param flags: decides which rules are applied to the interpretation of the addr value. See the netaddr.core namespace documentation for supported constant values. TrNflags) isinstancercidrr%rdictfromkeysrr$ iter_cidrsr rrrselfiterabler) mergeableaddrr+rrr__init__]s&        zIPSet.__init__cCtdd|jDS)z.:return: Pickled state of an ``IPSet`` object.cSsg|]}|qSr) __getstate__.0r+rrr ~z&IPSet.__getstate__..)tupler%r0rrrr6|szIPSet.__getstate__cCstdd|Dd|_dS)zR :param state: data used to unpickle a pickled ``IPSet`` object. css&|]\}}}t||f|dVqdS))r N)r)r8value prefixlenr rrr sz%IPSet.__setstate__..TN)r,r-r%)r0staterrr __setstate__s  zIPSet.__setstate__cCsj|j}|j}|j}|j|jjkr$|D]}||jvr"|j|=dSqnCg}|jD]4}|jj|ks5||kr6q)|j}|j} ||krJ| |krJ||q)||kr]| |kr]|j|=|rZJdSq)|D]} |j| =q`|jj|j } |j dkr|j | ?d@} | r| } n| } | |jvrdS|j| =|j|=|j d8_ | d7} |j | ?| >|_ d|j|<|j dkssdSdS)a Same as compact(), but assume that added_network is the only change and that this IPSet was properly compacted before added_network was added. This allows to perform compaction much faster. added_network must already be present in self._cidrs. Nrr T) rrr _prefixlenr widthrr%rr>_valuepreviousnext)r0 added_network added_first added_last added_versionpotential_supernet to_remover+rritem shift_widththe_bit candidaterrr_compact_single_networksP         zIPSet._compact_single_networkcCst|j}t|d|_dS)zR Compact internal list of `IPNetwork` objects using a CIDR merge. TN)rr%r,r-r0cidrsrrrcompacts z IPSet.compactcCstd)z Raises ``TypeError`` if this method is called. .. note:: IPSet objects are not hashable and cannot be used as dictionary keys or as members of other sets. zIP sets are unhashable!) TypeErrorr<rrr__hash__szIPSet.__hash__cCsBt|}||jvr dS|jr|jd8_||jvrdS|jsdS)z :param ip: An IP address or subnet. :return: ``True`` if IP address or subnet is a member of this IP set. Tr F)rr%rB)r0iprrrr __contains__s  zIPSet.__contains__cC t|jS)z9Return True if IPSet contains at least one IP, else False)boolr%r<rrr __nonzero__ zIPSet.__nonzero__cCstjt|jS)zP :return: an iterator over the IP addresses within this IP set. ) _itertoolschainsortedr%r<rrr__iter__szIPSet.__iter__cCrY)zU :return: an iterator over individual IP subnets within this IP set. r_r%r<rrrr.s zIPSet.iter_cidrscCst|trtt|d|dd}|j||dSt|tr'|j }nt|t r5tt ||d}nt|}d|j|<| |dS)a< Adds an IP address or subnet or IPRange to this IP set. Has no effect if it is already present. Note that where possible the IP address or subnet is merged with other members of the set to form more concise CIDR blocks. :param addr: An IP address or subnet in either string or object form, or an IPRange object. :param flags: decides which rules are applied to the interpretation of the addr value. See the netaddr.core namespace documentation for supported constant values. rr'TNr() r*rr,r-rr%updaterTrr+r rrQ)r0r3r) new_cidrsrrradd s     z IPSet.addcCst|trt|d|d}|D]}||qdSt|tr&t||d}nt|}||d}d}|jD]}||vrEt ||}|}nq6|durX|j|=|D] }d|j|<qPdSdS)a  Removes an IP address or subnet or IPRange from this IP set. Does nothing if it is not already a member. Note that this method behaves more like discard() found in regular Python sets because it doesn't raise KeyError exceptions if the IP address or subnet is question does not exist. It doesn't make sense to fully emulate that behaviour here as IP sets contain groups of individual IP addresses as individual set members using IPNetwork objects. :param addr: An IP address or subnet, or an IPRange. :param flags: decides which rules are applied to the interpretation of the addr value. See the netaddr.core namespace documentation for supported constant values. rr'Nr(T) r*rrremover rrrdr%r)r0r3r)rSr+ remainder matching_cidrrrrre*s.       z IPSet.removecCs|jdS)z Removes and returns an arbitrary IP address or subnet from this IP set. :return: An IP address or subnet. r)r%popitemr<rrrpopbsz IPSet.popcCs||}| S)z :param other: an IP set. :return: ``True`` if this IP set has no elements (IP addresses or subnets) in common with other. Intersection *must* be an empty set. ) intersection)r0otherresultrrr isdisjointks zIPSet.isdisjointcCs|}|j|j|S)z':return: a shallow copy of this IP set.) __class__r%rb)r0obj_copyrrrcopyvsz IPSet.copycCst|trtddtt|jt|jDd|_dSt|ttfr+| |dSt |ds4t dg}|D]}t|t rEt ||d}||q8tt|j|D]}d|j|<qT|dS)a~ Update the contents of this IP set with the union of itself and other IP set. :param iterable: an iterable containing IP addresses, subnets or ranges. :param flags: decides which rules are applied to the interpretation of the addr value. See the netaddr.core namespace documentation for supported constant values. css|]}|VqdS)Nr)r8rWrrrr?szIPSet.update..TNr`zan iterable was expected!r()r*r$r,r-rr r%rrrdhasattrrUr rrrTr/rrrrb|s*        z IPSet.updatecCs i|_dS)z5Remove all IP addresses and subnets from this IP set.Nr%r<rrrclearr\z IPSet.clearcCs&z|j|jkWStytYSw)z :param other: an IP set :return: ``True`` if this IP set is equivalent to the ``other`` IP set, ``False`` otherwise. r%AttributeErrorNotImplementedr0rkrrr__eq__  z IPSet.__eq__cCs&z|j|jkWStytYSw)z :param other: an IP set :return: ``False`` if this IP set is equivalent to the ``other`` IP set, ``True`` otherwise. rtrwrrr__ne__ryz IPSet.__ne__cCs$t|dstS|j|jko||S)z :param other: an IP set :return: ``True`` if this IP set is less than the ``other`` IP set, ``False`` otherwise. r%)rqrvsizeissubsetrwrrr__lt__ z IPSet.__lt__cCs|jD] }||vr dSqdS)z :param other: an IP set. :return: ``True`` if every IP address and subnet in this IP set is found within ``other``. FTrrr0rkr+rrrr|s zIPSet.issubsetcCs$t|dstS|j|jko||S)z :param other: an IP set. :return: ``True`` if this IP set is greater than the ``other`` IP set, ``False`` otherwise. r%)rqrvr{ issupersetrwrrr__gt__r~z IPSet.__gt__cCs,t|dstS|jD] }||vrdSq dS)z :param other: an IP set. :return: ``True`` if every IP address and subnet in other IP set is found within this one. r%FT)rqrvr%rrrrrs  zIPSet.issupersetcCs|}|||S)z :param other: an IP set. :return: the union of this IP set and another as a new IP set (combines IP addresses and subnets from both sets). )rprb)r0rkip_setrrrunions z IPSet.unionc Csi}t|j}t|j}d}d}t|}t|}||krh||krh||} ||} | | kr9d|| <|d7}|d7}n'| | vrFd|| <|d7}n| | vrSd|| <|d7}n | | kr\|d7}n|d7}||krh||ks t} || _| S)z :param other: an IP set. :return: the intersection of this IP set and another as a new IP set. (IP addresses and subnets common to both sets). rTr )r_r%rr$) r0rk result_cidrsown_nets other_netsown_idx other_idxown_len other_lenown_cur other_currlrrrrjs6      zIPSet.intersectioncCsg}t|j}t|j}d}d}t|}t|}||kr||kr||} ||} | | kr5|d7}|d7}nE| | vrEt| |||}|d7}n5| | vrUt| |||}|d7}n%| | krj|| jj| j| jf|d7}n|| jj| j| jf|d7}||kr||ks ||kr||} || jj| j| jf|d7}||ks||kr||} || jj| j| jf|d7}||kst } t |D]\} } t | | }|D]}d| j|<qq| S)z :param other: an IP set. :return: the symmetric difference of this IP set and another as a new IP set (all IP addresses and subnets that are in exactly one of the sets). rr T) r_r%rrrr r rrr$r#r)r0rk result_rangesrrrrrrrrrlstartstoprSr+rrrsymmetric_difference+sd            zIPSet.symmetric_differencecCs0g}i}t|j}t|j}d}d}t|}t|} ||kri|| kri||} ||} | | kr7|d7}|d7}n*| | vr@|d7}n!| | vrPt| |||}|d7}n| | kr]d|| <|d7}n|d7}||kri|| ks"||kr{d|||<|d7}||ksmt|D]\} } t| | D]}d||<qqt}||_|S)z :param other: an IP set. :return: the difference between this IP set and another as a new IP set (all IP addresses and subnets that are in this IP set but not found in the other.) rr T)r_r%rrr#rr$)r0rkrrrrrrrrrrrrr+rlrrr differenceosJ        zIPSet.differencecCs|j}|tkr tdt|S)z :return: the cardinality of this IP set (i.e. sum of individual IP addresses). Raises ``IndexError`` if size > maxint (a Python limitation). Use the .size property for subnets of any size. zUrange contains more than %d (sys.maxint) IP addresses!Use the .size property instead.)r{r IndexError)r0r{rrr__len__sz IPSet.__len__cCr5)z The cardinality of this IP set (based on the number of individual IP addresses including those implicitly defined in subnets). cSsg|]}|jqSr)r{r7rrrr9szIPSet.size..)sumr%r<rrrr{sz IPSet.sizecCsdddt|jDS)z8:return: Python statement to create an equivalent objectz IPSet(%r)cSsg|]}t|qSr)str)r8crrrr9r:z"IPSet.__repr__..rar<rrr__repr__szIPSet.__repr__cCsL|}t|dkr$|dd}|D]}|d|krdS|dd}qdS)z Returns True if the members of the set form a contiguous IP address range (with no gaps), False otherwise. :return: ``True`` if the ``IPSet`` object is contiguous. r rFr'T)r.r)r0rSrEr+rrr iscontiguouss   zIPSet.iscontiguouscCs:|r|}|s dSt|dd|ddStd)z Generates an IPRange for this IPSet, if all its members form a single contiguous sequence. Raises ``ValueError`` if the set is not contiguous. :return: An ``IPRange`` for all IPs in the IPSet. Nrr'zIPSet is not contiguous)rr.r ValueErrorrRrrripranges  z IPSet.iprangeccs6dd|D}t|D] \}}t||VqdS)zGenerate the merged IPRanges for this IPSet. In contrast to self.iprange(), this will work even when the IPSet is not contiguous. Adjacent IPRanges will be merged together, so you get the minimal number of IPRanges. cSsg|] }|jj|j|jfqSr)r r rrr7rrrr9sz'IPSet.iter_ipranges..N)r.r#r)r0rrrrrr iter_iprangesszIPSet.iter_ipranges)Nr)r)/__name__ __module__ __qualname____doc__ __slots__r4r6rArQrTrVrXr[__bool__r`r.rdrerirmrprbrsrxrzr}r|__le__rr__ge__r__or__rj__and__r__xor__r__sub__rpropertyr{r__str__rrrrrrrr$UsZ  J   !8  #      *B4  r$)r itertoolsr] netaddr.iprrrrrrnetaddr.compatrr r rr#objectr$rrrrs (