o
    TiJ                     @   s.  d Z ddlmZ ddlZddlmZ ddlmZ ddlm	Z	m
Z
mZmZmZmZ ddlmZ ed	Zed
ZedZddddddddZedD ]Zeeedef  qKdD ]Zee
edef  q[eZee	dfddZefddZeZG dd deZ ee!eee"e#e$ee%e&e'e(fddZ)dS ) zImplementation of JSONEncoder
    )absolute_importN)
itemgetterDecimal   )uunichrbinary_typestring_typesinteger_typesPY3)PosInfu   [\x00-\x1f\\"\b\f\n\r\t  ]z([\\"]|[^\ -~])z[\x80-\xff]z\\z\"z\bz\fz\nz\rz\t)\"
	    \u%04x)i(   i)   r   c                 C   sX   |rt | tr| d} nt | trt| dur| d} dd }|t||  | S )z5Return a JSON representation of a Python string

    utf-8Nc                 S   s   t | d S )Nr   )
ESCAPE_DCTgroup)match r   A/home/ubuntu/.local/lib/python3.10/site-packages/hjson/encoder.pyreplace+   s   z"encode_basestring.<locals>.replace)
isinstancer	   decodestrHAS_UTF8searchESCAPEsub)s_PY3_qr   r   r   r   encode_basestring!   s   


r(   c                 C   s\   |rt | tr| d} nt | trt| dur| d} dd }dtt||  d S )zAReturn an ASCII-only JSON representation of a Python string

    r   Nc                 S   sv   |  d}zt| W S  ty:   t|}|dk r d|f  Y S |d8 }d|d? d@ B }d|d@ B }d||f  Y S w )	Nr   i   r   i   
   i  i   z\u%04x\u%04x)r   r   KeyErrorord)r   r%   ns1s2r   r   r   r   :   s   

z+py_encode_basestring_ascii.<locals>.replacer   )r   r	   r   r    r!   r"   ESCAPE_ASCIIr$   )r%   r&   r   r   r   r   py_encode_basestring_ascii0   s   


r0   c                   @   sJ   e Zd ZdZdZdZ							ddd	Zd
d Zdd ZdddZ	dS )JSONEncoderaZ  Extensible JSON <http://json.org> encoder for Python data structures.

    Supports the following objects and types by default:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict, namedtuple  | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str, unicode      | string        |
    +-------------------+---------------+
    | int, long, float  | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

    To extend this to recognize other objects, subclass and implement a
    ``.default()`` method with another method that returns a serializable
    object for ``o`` if possible, otherwise it should call the superclass
    implementation (to raise ``TypeError``).

    z, z: FTNr   c                 C   s   || _ || _|| _|| _|	| _|
| _|| _|| _|| _|| _	|| _
|dur.t|ts.|d }|| _|dur<|\| _| _n|durCd| _|durJ|| _|| _dS )a  Constructor for JSONEncoder, with sensible defaults.

        If skipkeys is false, then it is a TypeError to attempt
        encoding of keys that are not str, int, long, float or None.  If
        skipkeys is True, such items are simply skipped.

        If ensure_ascii is true, the output is guaranteed to be str
        objects with all incoming unicode characters escaped.  If
        ensure_ascii is false, the output will be unicode object.

        If check_circular is true, then lists, dicts, and custom encoded
        objects will be checked for circular references during encoding to
        prevent an infinite recursion (which would cause an OverflowError).
        Otherwise, no such check takes place.

        If sort_keys is true, then the output of dictionaries will be
        sorted by key; this is useful for regression tests to ensure
        that JSON serializations can be compared on a day-to-day basis.

        If indent is a string, then JSON array elements and object members
        will be pretty-printed with a newline followed by that string repeated
        for each level of nesting. ``None`` (the default) selects the most compact
        representation without any newlines. For backwards compatibility with
        versions of hjson earlier than 2.1.0, an integer is also accepted
        and is converted to a string with that many spaces.

        If specified, separators should be an (item_separator, key_separator)
        tuple.  The default is (', ', ': ') if *indent* is ``None`` and
        (',', ': ') otherwise.  To get the most compact JSON representation,
        you should specify (',', ':') to eliminate whitespace.

        If specified, default is a function that gets called for objects
        that can't otherwise be serialized.  It should return a JSON encodable
        version of the object or raise a ``TypeError``.

        If encoding is not None, then all input strings will be
        transformed into unicode using that encoding prior to JSON-encoding.
        The default is UTF-8.

        If use_decimal is true (not the default), ``decimal.Decimal`` will
        be supported directly by the encoder. For the inverse, decode JSON
        with ``parse_float=decimal.Decimal``.

        If namedtuple_as_object is true (the default), objects with
        ``_asdict()`` methods will be encoded as JSON objects.

        If tuple_as_array is true (the default), tuple (and subclasses) will
        be encoded as JSON arrays.

        If bigint_as_string is true (not the default), ints 2**53 and higher
        or lower than -2**53 will be encoded as strings. This is to avoid the
        rounding that happens in Javascript otherwise.

        If int_as_string_bitcount is a positive number (n), then int of size
        greater than or equal to 2**n or lower than or equal to -2**n will be
        encoded as strings.

        If specified, item_sort_key is a callable used to sort the items in
        each dictionary. This is useful if you want to sort items other than
        in alphabetical order by key.

        If for_json is true (not the default), objects with a ``for_json()``
        method will use the return value of that method for encoding as JSON
        instead of the object.

        N ,)skipkeysensure_asciicheck_circular	sort_keysuse_decimalnamedtuple_as_objecttuple_as_arraybigint_as_stringitem_sort_keyfor_jsonint_as_string_bitcountr   r
   indentitem_separatorkey_separatordefaultencoding)selfr4   r5   r6   r7   r?   
separatorsrC   rB   r8   r9   r:   r;   r<   r=   r>   r   r   r   __init__p   s*   J
zJSONEncoder.__init__c                 C   s   t t|d )a$  Implement this method in a subclass such that it returns
        a serializable object for ``o``, or calls the base implementation
        (to raise a ``TypeError``).

        For example, to support arbitrary iterators, you could
        implement default like this::

            def default(self, o):
                try:
                    iterable = iter(o)
                except TypeError:
                    pass
                else:
                    return list(iterable)
                return JSONEncoder.default(self, o)

        z is not JSON serializable)	TypeErrorrepr)rD   or   r   r   rB      s   zJSONEncoder.defaultc                 C   s   t |tr| j}|dur|dks||}t |tr%| jr!t|S t|S | j|dd}t |t	t
fs7t	|}| jr?d|S d|S )zReturn a JSON string representation of a Python data structure.

        >>> from hjson import JSONEncoder
        >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
        '{"foo": ["bar", "baz"]}'

        Nr   T)	_one_shot )r   r	   rC   r   r
   r5   encode_basestring_asciir(   
iterencodelisttuplejoin)rD   rI   	_encodingchunksr   r   r   encode   s   
	



zJSONEncoder.encodec           	      C   s   | j ri }nd}| jrt}nt}| jdkr|| jfdd}ttt fdd}i }| jr-dn| j}t	|| j
|| j|| j| j| j| j|| j| j| j|| j| j| jtd}z
||d	W |  S |  w )
zEncode the given object and yield each string
        representation as available.

        For example::

            for chunk in JSONEncoder().iterencode(bigobject):
                mysocket.write(chunk)

        Nr   c                 S   s   t | tr
| |} || S )N)r   r	   r   )rI   _orig_encoderrQ   r   r   r   _encoder  s   

z(JSONEncoder.iterencode.<locals>._encoderc                 S   s8   | | krd}|S | |krd}|S | |krd}|S || S )Nnullr   )rI   _repr_inf_neginftextr   r   r   floatstr  s   z(JSONEncoder.iterencode.<locals>.floatstr5   r   r   )r6   r5   rL   r(   rC   
FLOAT_REPRr   r;   r>   _make_iterencoderB   r?   rA   r@   r7   r4   r8   r9   r:   r<   r=   r   clear)	rD   rI   rJ   markersrU   r[   key_memor>   _iterencoder   r   r   rM     s0   



zJSONEncoder.iterencode)FTTFNNr   NTTTFNFN)F)
__name__
__module____qualname____doc__r@   rA   rF   rB   rS   rM   r   r   r   r   r1   P   s    
`r1   c                    s   r
t s
td|rstd
d ur#
dks
s#td
fdd	fdd f
dd		fd
d fddS )Nz&item_sort_key must be None or callabler   z1int_as_string_bitcount must be a positive integerc                    sR    d u p dk }|sd > |   k rd > k r!| S  n| S d|  d S )Nr   r   r   )valueskip_quoting)_int_as_string_bitcountr    r   r   _encode_intW  s   z%_make_iterencode.<locals>._encode_intc           	      3   s    | sdV  d S d ur| }|v r d| |< d}d ur5|d7 }d|  }| }||7 }nd }}d}| D ]}|rDd}n|}|V  ||D ]}|V  qNq=|d urd|d8 }d|  V  dV  d urp|= d S d S )	Nz[]Circular reference detected[r   r   TF]r   )	lst_current_indent_levelmarkeridbufnewline_indent	separatorfirstrh   chunk)
ValueError_indent_item_separatorrb   idr`   r   r   _iterencode_listf  sB   

z*_make_iterencode.<locals>._iterencode_listc                    s   | 	r	 | S | t r| } | S | r| } | S | du r'd} | S | du r/d} | S | d u r7d} | S | rB| } | S rO|  rO| } | S rUd } | S tdt|  d )NTtrueFfalserV   zkey z is not a string)r	   r   rG   rH   key)
r   rQ   	_floatstr	_skipkeys_use_decimalfloatr   r   r    r
   r   r   _stringify_key  s8   



	
z(_make_iterencode.<locals>._stringify_keyc                 3   s   | sdV  d S d ur	| }|v r d| |< dV  d ur5|d7 }d|  }| }|V  nd }}d}rB|   }n|  }rog }|   D ]\}}	
|s`|}|d u r`qN|||	f qN|jd n|}|D ]/\}
}s
|
s|
}
|
d u rqs|rd}n|V  |
V  V  ||D ]}|V  qqs|d ur|d8 }d|  V  d	V  d ur|= d S d S )
Nz{}rl   {r   r   Tr~   F})items	iteritemsappendsort)dctrp   rq   rs   r@   ru   r   r   kvr   rh   rv   )rw   r&   rU   rx   ry   _item_sort_keyrb   _key_separatorr   rz   r   r`   r
   r   r   _iterencode_dict  sf   



z*_make_iterencode.<locals>._iterencode_dictc                 3   s   | sr| t r| V  d S | d u rdV  d S | du r&dV  d S | du r/dV  d S | r;| V  d S | rG| V  d S oNt| dd }|rct|rc| |D ]}|V  q[d S | ru
| |D ]}|V  qmd S o|t| dd }|rt|r	| |D ]}|V  qd S r| r
| |D ]}|V  qd S | r	| |D ]}|V  qd S rň|  rň| V  d S d urو| }|v rՈd| |< | } | |D ]}|V  qd ur|= d S d S )	NrV   Tr|   Fr}   r=   _asdictrl   )r	   getattrcallable)rI   rp   r=   rv   r   rq   )r   rw   r&   _defaultrk   rU   r   	_for_jsonrb   r   r{   _namedtuple_as_object_tuple_as_arrayr   dictr   rz   r   r   rN   r`   r    r
   rO   r   r   rb     sh   








z%_make_iterencode.<locals>._iterencode)r   rG   r   )r`   r   rU   rx   r   r   ry   
_sort_keysr   rJ   r   r   r   rj   r   rQ   r   r&   rw   r
   r   r   r   rz   r   r   rN   r    rO   r   ) r   rw   r&   r   rk   rU   rQ   r   r   rx   rj   ry   r   rb   r   r{   r   r   r   r   r   r   r   r   rz   r   r   rN   r`   r    r
   rO   r   r^   :  s   $$:9/r^   )*rf   
__future__r   reoperatorr   decimalr   compatr   r   r	   r
   r   r   decoderr   compiler#   r/   r!   r   rangei
setdefaultchrrH   r]   r(   r0   rL   objectr1   rw   r   r   rz   r   rN   r    rO   r^   r   r   r   r   <module>   sT     


	 q