U
    SctV                  	   @   s  d dl Z d dlmZ ddddddd	d
dg	ZG dd deZG dd deZG dd deZG dd deZG dd deZ	G dd deZ
G dd deZG dd deZG dd deZG dd deZG dd	 d	eZG dd deZG dd
 d
eZG dd deZdS )    N)errorSingleValueConstraintContainedSubtypeConstraintValueRangeConstraintValueSizeConstraintPermittedAlphabetConstraintInnerTypeConstraintConstraintsExclusionConstraintsIntersectionConstraintsUnionc                   @   s   e Zd Zdd Zd&ddZdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dd Zejd dkrjdd Zndd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% ZdS )'AbstractConstraintc                 G   s*   t  | _| | t| jj| jf| _d S N)set	_valueMap
_setValueshash	__class____name___values_AbstractConstraint__hashselfvalues r   :/tmp/pip-unpacked-wheel-hsjy238j/pyasn1/type/constraint.py__init__   s    
zAbstractConstraint.__init__Nc              	   C   sP   | j s
d S z| || W n0 tjk
rJ   td| t d f Y nX d S )Nz%s failed at: %r   )r   
_testValuer   ValueConstraintErrorsysexc_infor   valueidxr   r   r   __call__   s    zAbstractConstraint.__call__c                 C   s8   d| j j }| jr0|dddd | jD  7 }d| S )Nz	%s objectz, consts %sz, c                 S   s   g | ]}t |qS r   )repr).0xr   r   r   
<listcomp>,   s     z/AbstractConstraint.__repr__.<locals>.<listcomp>z<%s>)r   r   r   join)r   Zrepresentationr   r   r   __repr__'   s    zAbstractConstraint.__repr__c                 C   s   | |krdp| j |kS )NTr   r   otherr   r   r   __eq__0   s    zAbstractConstraint.__eq__c                 C   s
   | j |kS r   r+   r,   r   r   r   __ne__3   s    zAbstractConstraint.__ne__c                 C   s
   | j |k S r   r+   r,   r   r   r   __lt__6   s    zAbstractConstraint.__lt__c                 C   s
   | j |kS r   r+   r,   r   r   r   __le__9   s    zAbstractConstraint.__le__c                 C   s
   | j |kS r   r+   r,   r   r   r   __gt__<   s    zAbstractConstraint.__gt__c                 C   s
   | j |kS r   r+   r,   r   r   r   __ge__?   s    zAbstractConstraint.__ge__r      c                 C   s   | j r
dpdS NTFr+   r   r   r   r   __nonzero__C   s    zAbstractConstraint.__nonzero__c                 C   s   | j r
dpdS r5   r+   r6   r   r   r   __bool__F   s    zAbstractConstraint.__bool__c                 C   s   | j S r   )r   r6   r   r   r   __hash__I   s    zAbstractConstraint.__hash__c                 C   s
   || _ d S r   r+   r   r   r   r   r   L   s    zAbstractConstraint._setValuesc                 C   s   t |d S r   r   r   r!   r   r   r   r   O   s    zAbstractConstraint._testValuec                 C   s   | j S r   r   r6   r   r   r   getValueMapS   s    zAbstractConstraint.getValueMapc                 C   s$   || kp"| j  p"|| kp"| | kS r   )r   r<   r   ZotherConstraintr   r   r   isSuperTypeOfV   s    
z AbstractConstraint.isSuperTypeOfc                 C   s    || kp|  p|| kp|| j kS r   r;   r=   r   r   r   isSubTypeOf]   s    zAbstractConstraint.isSubTypeOf)N)r   
__module____qualname__r   r$   r*   r.   r/   r0   r1   r2   r3   r   version_infor7   r8   r9   r   r   r<   r>   r?   r   r   r   r   r      s$   
	
r   c                   @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd ZdS )r   a  Create a SingleValueConstraint object.

    The SingleValueConstraint satisfies any value that
    is present in the set of permitted values.

    Objects of this type are iterable (emitting constraint values) and
    can act as operands for some arithmetic operations e.g. addition
    and subtraction. The latter can be used for combining multiple
    SingleValueConstraint objects into one.

    The SingleValueConstraint object can be applied to
    any ASN.1 type.

    Parameters
    ----------
    *values: :class:`int`
        Full set of values permitted by this constraint object.

    Examples
    --------
    .. code-block:: python

        class DivisorOfSix(Integer):
            '''
            ASN.1 specification:

            Divisor-Of-6 ::= INTEGER (1 | 2 | 3 | 6)
            '''
            subtypeSpec = SingleValueConstraint(1, 2, 3, 6)

        # this will succeed
        divisor_of_six = DivisorOfSix(1)

        # this will raise ValueConstraintError
        divisor_of_six = DivisorOfSix(7)
    c                 C   s   || _ t|| _d S r   r   r   _setr   r   r   r   r      s    z SingleValueConstraint._setValuesc                 C   s   || j krt|d S r   )rD   r   r   r!   r   r   r   r      s    
z SingleValueConstraint._testValuec                 C   s
   || j kS r   )rD   )r   itemr   r   r   __contains__   s    z"SingleValueConstraint.__contains__c                 C   s
   t | jS r   )iterrD   r6   r   r   r   __iter__   s    zSingleValueConstraint.__iter__c                 C   s   | j | j| S r   r   rD   
differencer   
constraintr   r   r   __sub__   s    zSingleValueConstraint.__sub__c                 C   s   | j | j| S r   )r   rD   unionrK   r   r   r   __add__   s    zSingleValueConstraint.__add__c                 C   s   | j | j| S r   rI   rK   r   r   r   rM      s    N)
r   r@   rA   __doc__r   r   rF   rH   rM   rO   r   r   r   r   r   d   s   $c                   @   s   e Zd ZdZdd ZdS )r   a  Create a ContainedSubtypeConstraint object.

    The ContainedSubtypeConstraint satisfies any value that
    is present in the set of permitted values and also
    satisfies included constraints.

    The ContainedSubtypeConstraint object can be applied to
    any ASN.1 type.

    Parameters
    ----------
    *values:
        Full set of values and constraint objects permitted
        by this constraint object.

    Examples
    --------
    .. code-block:: python

        class DivisorOfEighteen(Integer):
            '''
            ASN.1 specification:

            Divisors-of-18 ::= INTEGER (INCLUDES Divisors-of-6 | 9 | 18)
            '''
            subtypeSpec = ContainedSubtypeConstraint(
                SingleValueConstraint(1, 2, 3, 6), 9, 18
            )

        # this will succeed
        divisor_of_eighteen = DivisorOfEighteen(9)

        # this will raise ValueConstraintError
        divisor_of_eighteen = DivisorOfEighteen(10)
    c                 C   s:   | j D ].}t|tr ||| q|| jkrt|qd S r   )r   
isinstancer   rD   r   r   r   r"   r#   rL   r   r   r   r      s
    


z%ContainedSubtypeConstraint._testValueNr   r@   rA   rP   r   r   r   r   r   r      s   #c                   @   s    e Zd ZdZdd Zdd ZdS )r   a{  Create a ValueRangeConstraint object.

    The ValueRangeConstraint satisfies any value that
    falls in the range of permitted values.

    The ValueRangeConstraint object can only be applied
    to :class:`~pyasn1.type.univ.Integer` and
    :class:`~pyasn1.type.univ.Real` types.

    Parameters
    ----------
    start: :class:`int`
        Minimum permitted value in the range (inclusive)

    end: :class:`int`
        Maximum permitted value in the range (inclusive)

    Examples
    --------
    .. code-block:: python

        class TeenAgeYears(Integer):
            '''
            ASN.1 specification:

            TeenAgeYears ::= INTEGER (13 .. 19)
            '''
            subtypeSpec = ValueRangeConstraint(13, 19)

        # this will succeed
        teen_year = TeenAgeYears(18)

        # this will raise ValueConstraintError
        teen_year = TeenAgeYears(20)
    c                 C   s"   || j k s|| jkrt|d S r   )startstopr   r   r!   r   r   r   r      s    zValueRangeConstraint._testValuec                 C   sd   t |dkr td| jjf |\| _| _| j| jkrTtd| jj| j| jf t| | d S )Nr4   z%s: bad constraint valuesz5%s: screwed constraint values (start > stop): %s > %s)	lenr   PyAsn1Errorr   r   rT   rU   r   r   r   r   r   r   r      s     zValueRangeConstraint._setValuesNr   r@   rA   rP   r   r   r   r   r   r   r      s   #c                   @   s   e Zd ZdZdd ZdS )r   a  Create a ValueSizeConstraint object.

    The ValueSizeConstraint satisfies any value for
    as long as its size falls within the range of
    permitted sizes.

    The ValueSizeConstraint object can be applied
    to :class:`~pyasn1.type.univ.BitString`,
    :class:`~pyasn1.type.univ.OctetString` (including
    all :ref:`character ASN.1 types <type.char>`),
    :class:`~pyasn1.type.univ.SequenceOf`
    and :class:`~pyasn1.type.univ.SetOf` types.

    Parameters
    ----------
    minimum: :class:`int`
        Minimum permitted size of the value (inclusive)

    maximum: :class:`int`
        Maximum permitted size of the value (inclusive)

    Examples
    --------
    .. code-block:: python

        class BaseballTeamRoster(SetOf):
            '''
            ASN.1 specification:

            BaseballTeamRoster ::= SET SIZE (1..25) OF PlayerNames
            '''
            componentType = PlayerNames()
            subtypeSpec = ValueSizeConstraint(1, 25)

        # this will succeed
        team = BaseballTeamRoster()
        team.extend(['Jan', 'Matej'])
        encode(team)

        # this will raise ValueConstraintError
        team = BaseballTeamRoster()
        team.extend(['Jan'] * 26)
        encode(team)

    Note
    ----
    Whenever ValueSizeConstraint is applied to mutable types
    (e.g. :class:`~pyasn1.type.univ.SequenceOf`,
    :class:`~pyasn1.type.univ.SetOf`), constraint
    validation only happens at the serialisation phase rather
    than schema instantiation phase (as it is with immutable
    types).
    c                 C   s*   t |}|| jk s|| jkr&t|d S r   )rV   rT   rU   r   r   )r   r"   r#   Z	valueSizer   r   r   r   =  s    zValueSizeConstraint._testValueNrS   r   r   r   r   r     s   5c                   @   s    e Zd ZdZdd Zdd ZdS )r   a	  Create a PermittedAlphabetConstraint object.

    The PermittedAlphabetConstraint satisfies any character
    string for as long as all its characters are present in
    the set of permitted characters.

    Objects of this type are iterable (emitting constraint values) and
    can act as operands for some arithmetic operations e.g. addition
    and subtraction.

    The PermittedAlphabetConstraint object can only be applied
    to the :ref:`character ASN.1 types <type.char>` such as
    :class:`~pyasn1.type.char.IA5String`.

    Parameters
    ----------
    *alphabet: :class:`str`
        Full set of characters permitted by this constraint object.

    Example
    -------
    .. code-block:: python

        class BooleanValue(IA5String):
            '''
            ASN.1 specification:

            BooleanValue ::= IA5String (FROM ('T' | 'F'))
            '''
            subtypeSpec = PermittedAlphabetConstraint('T', 'F')

        # this will succeed
        truth = BooleanValue('T')
        truth = BooleanValue('TF')

        # this will raise ValueConstraintError
        garbage = BooleanValue('TAF')

    ASN.1 `FROM ... EXCEPT ...` clause can be modelled by combining multiple
    PermittedAlphabetConstraint objects into one:

    Example
    -------
    .. code-block:: python

        class Lipogramme(IA5String):
            '''
            ASN.1 specification:

            Lipogramme ::=
                IA5String (FROM (ALL EXCEPT ("e"|"E")))
            '''
            subtypeSpec = (
                PermittedAlphabetConstraint(*string.printable) -
                PermittedAlphabetConstraint('e', 'E')
            )

        # this will succeed
        lipogramme = Lipogramme('A work of fiction?')

        # this will raise ValueConstraintError
        lipogramme = Lipogramme('Eel')

    Note
    ----
    Although `ConstraintsExclusion` object could seemingly be used for this
    purpose, practically, for it to work, it needs to represent its operand
    constraints as sets and intersect one with the other. That would require
    the insight into the constraint values (and their types) that are otherwise
    hidden inside the constraint object.

    Therefore it's more practical to model `EXCEPT` clause at
    `PermittedAlphabetConstraint` level instead.
    c                 C   s   || _ t|| _d S r   rC   r   r   r   r   r     s    z&PermittedAlphabetConstraint._setValuesc                 C   s   | j |st|d S r   )rD   
issupersetr   r   r!   r   r   r   r     s    z&PermittedAlphabetConstraint._testValueNr   r@   rA   rP   r   r   r   r   r   r   r   C  s   Jc                   @   s    e Zd ZdZdd Zdd ZdS )ComponentPresentConstrainta  Create a ComponentPresentConstraint object.

    The ComponentPresentConstraint is only satisfied when the value
    is not `None`.

    The ComponentPresentConstraint object is typically used with
    `WithComponentsConstraint`.

    Examples
    --------
    .. code-block:: python

        present = ComponentPresentConstraint()

        # this will succeed
        present('whatever')

        # this will raise ValueConstraintError
        present(None)
    c                 C   s   d| _ |rtdd S )N)z<must be present>No arguments expectedr   r   rW   r   r   r   r   r     s    z%ComponentPresentConstraint._setValuesc                 C   s   |d krt dd S )NzComponent is not present:r:   r!   r   r   r   r     s    z%ComponentPresentConstraint._testValueNrZ   r   r   r   r   r[     s   r[   c                   @   s    e Zd ZdZdd Zdd ZdS )ComponentAbsentConstrainta  Create a ComponentAbsentConstraint object.

    The ComponentAbsentConstraint is only satisfied when the value
    is `None`.

    The ComponentAbsentConstraint object is typically used with
    `WithComponentsConstraint`.

    Examples
    --------
    .. code-block:: python

        absent = ComponentAbsentConstraint()

        # this will succeed
        absent(None)

        # this will raise ValueConstraintError
        absent('whatever')
    c                 C   s   d| _ |rtdd S )N)z<must be absent>r\   r]   r   r   r   r   r     s    z$ComponentAbsentConstraint._setValuesc                 C   s   |d k	rt d| d S )NzComponent is not absent: %rr:   r!   r   r   r   r     s    z$ComponentAbsentConstraint._testValueNrZ   r   r   r   r   r^     s   r^   c                   @   s    e Zd ZdZdd Zdd ZdS )WithComponentsConstrainta&	  Create a WithComponentsConstraint object.

    The `WithComponentsConstraint` satisfies any mapping object that has
    constrained fields present or absent, what is indicated by
    `ComponentPresentConstraint` and `ComponentAbsentConstraint`
    objects respectively.

    The `WithComponentsConstraint` object is typically applied
    to  :class:`~pyasn1.type.univ.Set` or
    :class:`~pyasn1.type.univ.Sequence` types.

    Parameters
    ----------
    *fields: :class:`tuple`
        Zero or more tuples of (`field`, `constraint`) indicating constrained
        fields.

    Notes
    -----
    On top of the primary use of `WithComponentsConstraint` (ensuring presence
    or absence of particular components of a :class:`~pyasn1.type.univ.Set` or
    :class:`~pyasn1.type.univ.Sequence`), it is also possible to pass any other
    constraint objects or their combinations. In case of scalar fields, these
    constraints will be verified in addition to the constraints belonging to
    scalar components themselves. However, formally, these additional
    constraints do not change the type of these ASN.1 objects.

    Examples
    --------

    .. code-block:: python

        class Item(Sequence):  #  Set is similar
            '''
            ASN.1 specification:

            Item ::= SEQUENCE {
                id    INTEGER OPTIONAL,
                name  OCTET STRING OPTIONAL
            } WITH COMPONENTS id PRESENT, name ABSENT | id ABSENT, name PRESENT
            '''
            componentType = NamedTypes(
                OptionalNamedType('id', Integer()),
                OptionalNamedType('name', OctetString())
            )
            withComponents = ConstraintsUnion(
                WithComponentsConstraint(
                    ('id', ComponentPresentConstraint()),
                    ('name', ComponentAbsentConstraint())
                ),
                WithComponentsConstraint(
                    ('id', ComponentAbsentConstraint()),
                    ('name', ComponentPresentConstraint())
                )
            )

        item = Item()

        # This will succeed
        item['id'] = 1

        # This will succeed
        item.reset()
        item['name'] = 'John'

        # This will fail (on encoding)
        item.reset()
        descr['id'] = 1
        descr['name'] = 'John'
    c                 C   s"   | j D ]\}}||| qd S r   )r   get)r   r"   r#   fieldrL   r   r   r   r      s    z#WithComponentsConstraint._testValuec                 C   s   t | | d S r   r   r   r   r   r   r   r   $  s    z#WithComponentsConstraint._setValuesNrX   r   r   r   r   r_     s   Fr_   c                   @   s    e Zd ZdZdd Zdd ZdS )r   z4Value must satisfy the type and presence constraintsc                 C   sX   | j r|  | nB| jrT|| jkr,t|| j| \}}|dkrLt||| d S )NZABSENT)*_InnerTypeConstraint__singleTypeConstraint,_InnerTypeConstraint__multipleTypeConstraintr   r   )r   r"   r#   rL   statusr   r   r   r   ,  s    


zInnerTypeConstraint._testValuec                 C   sR   i | _ d | _|D ]0}t|tr:|d |d f| j |d < q|| _qt| | d S )Nr   r4   r   )rd   rc   rQ   tupler   r   )r   r   vr   r   r   r   7  s    
zInnerTypeConstraint._setValuesNrX   r   r   r   r   r   )  s   c                   @   s    e Zd ZdZdd Zdd ZdS )r	   a  Create a ConstraintsExclusion logic operator object.

    The ConstraintsExclusion logic operator succeeds when the
    value does *not* satisfy the operand constraint.

    The ConstraintsExclusion object can be applied to
    any constraint and logic operator object.

    Parameters
    ----------
    *constraints:
        Constraint or logic operator objects.

    Examples
    --------
    .. code-block:: python

        class LuckyNumber(Integer):
            subtypeSpec = ConstraintsExclusion(
                SingleValueConstraint(13)
            )

        # this will succeed
        luckyNumber = LuckyNumber(12)

        # this will raise ValueConstraintError
        luckyNumber = LuckyNumber(13)

    Note
    ----
    The `FROM ... EXCEPT ...` ASN.1 clause should be modeled by combining
    constraint objects into one. See `PermittedAlphabetConstraint` for more
    information.
    c              	   C   sD   | j D ]8}z||| W n tjk
r2   Y qY nX t|qd S r   r   r   r   rR   r   r   r   r   g  s    

zConstraintsExclusion._testValuec                 C   s   t | | d S r   rb   r   r   r   r   r   q  s    zConstraintsExclusion._setValuesNrX   r   r   r   r   r	   D  s   "
c                   @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )AbstractConstraintSetc                 C   s
   | j | S r   r+   )r   r#   r   r   r   __getitem__w  s    z!AbstractConstraintSet.__getitem__c                 C   s
   t | jS r   )rG   r   r6   r   r   r   rH   z  s    zAbstractConstraintSet.__iter__c                 C   s   | j | j|f  S r   r   r   r   r"   r   r   r   rO   }  s    zAbstractConstraintSet.__add__c                 C   s   | j |f| j  S r   rk   rl   r   r   r   __radd__  s    zAbstractConstraintSet.__radd__c                 C   s
   t | jS r   )rV   r   r6   r   r   r   __len__  s    zAbstractConstraintSet.__len__c                 C   s4   || _ |D ]$}|r
| j| | j|  q
d S r   )r   r   addupdater<   )r   r   rL   r   r   r   r     s
    z AbstractConstraintSet._setValuesN)	r   r@   rA   rj   rH   rO   rm   rn   r   r   r   r   r   ri   u  s   ri   c                   @   s   e Zd ZdZdd ZdS )r
   a7  Create a ConstraintsIntersection logic operator object.

    The ConstraintsIntersection logic operator only succeeds
    if *all* its operands succeed.

    The ConstraintsIntersection object can be applied to
    any constraint and logic operator objects.

    The ConstraintsIntersection object duck-types the immutable
    container object like Python :py:class:`tuple`.

    Parameters
    ----------
    *constraints:
        Constraint or logic operator objects.

    Examples
    --------
    .. code-block:: python

        class CapitalAndSmall(IA5String):
            '''
            ASN.1 specification:

            CapitalAndSmall ::=
                IA5String (FROM ("A".."Z"|"a".."z"))
            '''
            subtypeSpec = ConstraintsIntersection(
                PermittedAlphabetConstraint('A', 'Z'),
                PermittedAlphabetConstraint('a', 'z')
            )

        # this will succeed
        capital_and_small = CapitalAndSmall('Hello')

        # this will raise ValueConstraintError
        capital_and_small = CapitalAndSmall('hello')
    c                 C   s   | j D ]}||| qd S r   r+   rR   r   r   r   r     s    
z"ConstraintsIntersection._testValueNrS   r   r   r   r   r
     s   &c                   @   s   e Zd ZdZdd ZdS )r   a  Create a ConstraintsUnion logic operator object.

    The ConstraintsUnion logic operator succeeds if
    *at least* a single operand succeeds.

    The ConstraintsUnion object can be applied to
    any constraint and logic operator objects.

    The ConstraintsUnion object duck-types the immutable
    container object like Python :py:class:`tuple`.

    Parameters
    ----------
    *constraints:
        Constraint or logic operator objects.

    Examples
    --------
    .. code-block:: python

        class CapitalOrSmall(IA5String):
            '''
            ASN.1 specification:

            CapitalOrSmall ::=
                IA5String (FROM ("A".."Z") | FROM ("a".."z"))
            '''
            subtypeSpec = ConstraintsUnion(
                PermittedAlphabetConstraint('A', 'Z'),
                PermittedAlphabetConstraint('a', 'z')
            )

        # this will succeed
        capital_or_small = CapitalAndSmall('Hello')

        # this will raise ValueConstraintError
        capital_or_small = CapitalOrSmall('hello!')
    c              	   C   sP   | j D ]0}z||| W n tjk
r.   Y qX  d S qtd| j |f d S )Nzall of %s failed for "%s"rh   rR   r   r   r   r     s    
zConstraintsUnion._testValueNrS   r   r   r   r   r     s   &)r   Zpyasn1.typer   __all__objectr   r   r   r   r   r   r[   r^   r_   r   r	   ri   r
   r   r   r   r   r   <module>	   s0      P?,8<T!!P1,